Skip to content Skip to sidebar Skip to footer

How Do I Use Javascript To Return The Number Of Days Holidays Between Two Dates Excluding Holidays?

I have a code that returns the number of days between two dates selected with jquery datapicker. I would like to add a function for holidays that will exclude all holidays in an ar

Solution 1:

Like said in comments, you will have to define the holiday array.

For this example, I defined two dates: 2016-11-23 and 2016-12-02

You can use a database or do it manually in script in order to maintain the relevant dates over time. This part is not explained here, but in the script, I used the default MySQL date format, which is YYYY-MM-DD. It it should be easy to get holiday dates from a database.

An additionnal function is used to convert current date into this MySQL date format, in order to compare it. Then, in the while loop, we check if the date is a holiday and, if so, set a boolean flag used in the condition to add a "business day" or not to the counter.

var holiday_array=["2016-11-23", "2016-12-02"];   // YYYY-MM-DD (Default MySQL date format)functiondateToMySQL (x){
    varMySQL_day = x.getDate();
    if(MySQL_day<10){
        MySQL_day = "0"+MySQL_day;      // Leading zero on day...
    }
    varMySQL_month = x.getMonth()+1;   // Months are zero-based.if(MySQL_month<10){
        MySQL_month = "0"+MySQL_month;  // Leading zero on month...
    }
    varMySQL_year = x.getYear()+1900;  // Years are 1900 based.varMySQL_date = MySQL_year+"-"+MySQL_month+"-"+MySQL_day;
    returnMySQL_date;
}

functioncalcBusinessDays(start, end) {
    // This makes no effort to account for holidays// Counts end day, does not count start day// make copies we can normalize without changing passed in objects    var start = newDate(start);
    var end = newDate(end);

    // initial totalvar totalBusinessDays = 0;

    // normalize both start and end to beginning of the day
    start.setHours(0,0,0,0);
    end.setHours(0,0,0,0);

    // Prepare loop's variablesvar current = newDate(start);
    current.setDate(current.getDate() + 1);
    var day;
    var holidayFound=false;

    // loop through each day, checkingwhile (current <= end) {
        //console.log("current: "+current);// Check if current is in the holiday arrayvarMySQLdate = dateToMySQL(current);
        console.log("MySQL date: "+MySQLdate);

        if($.inArray(MySQLdate,holiday_array)!=-1){
            console.log("                  ^----------- Holiday!!!");
            holidayFound=true;     // "flag"
        }

        // If current is monday to friday and NOT a holiday
        day = current.getDay();
        if (day >= 1 && day <= 5 && !holidayFound) {
            ++totalBusinessDays;
        }

        // For next iteration
        current.setDate(current.getDate() + 1);
        holidayFound=false;
    }
    return totalBusinessDays;
}

$(function() {
    $( "#start_date" ).datepicker({
        minDate:0,
        showOn: 'button',
        buttonImageOnly: true,
        buttonImage: 'http://www.nscale.net/forums/images/misc/Tab-Calendar.png',    //'images/calendar.png',beforeShowDay: $.datepicker.noWeekends
    });
    $( "#end_date" ).datepicker({
        minDate:0,
        showOn: 'button',
        buttonImageOnly: true,
        buttonImage: 'http://www.nscale.net/forums/images/misc/Tab-Calendar.png',    //'images/calendar.png',beforeShowDay: $.datepicker.noWeekends,
        onSelect: function (dateStr) {
            var max = $(this).datepicker('getDate'); // Get selected date
            $('#datepicker').datepicker('option', 'maxDate', max || '+1Y+12M'); // Set other max, default to +18 monthsvar start = $("#start_date").datepicker("getDate");
            var end = $("#end_date").datepicker("getDate");
            var days = (end - start) / (1000 * 60 * 60 * 24);
            var diff = calcBusinessDays(start,end);
            $("#leave_days").val(diff);

        }
    });
});

See in CodePen( Check the console ;) )

Solution 2:

You can use this logic:

Taking weekends as holidays inbetween

functionworkingDaysBetweenDates(startDate, endDate) {
    var millisecondsPerDay = 86400 * 1000; 
    startDate.setHours(0,0,0,1);  
    endDate.setHours(23,59,59,999);  
    var diff = endDate - startDate;     
    var days = Math.ceil(diff / millisecondsPerDay);
    
    // Subtract two weekend days for every week in betweenvar weeks = Math.floor(days / 7);
    days = days - (weeks * 2);

    // Handle special casesvar startDay = startDate.getDay();
    var endDay = endDate.getDay();
    
    // Remove weekend not previously removed.   if (startDay - endDay > 1)         
        days = days - 2;      
    
    // Remove start day if span starts on Sunday but ends before Saturdayif (startDay === 0 && endDay != 6)
        days = days - 1 ; 
            
    // Remove end day if span ends on Saturday but starts after Sundayif (endDay === 6 && startDay !== 0)
        days = days - 1  ;
    
    return days;
}

var a = newDate(2015, 10, 16); 
var b = newDate(2016, 01, 20);
var t = workingDaysBetweenDates(a,b);
alert(t);

Hope this helps!

Post a Comment for "How Do I Use Javascript To Return The Number Of Days Holidays Between Two Dates Excluding Holidays?"