Posted In: Java Script

JS: Finding Number Of Working Days between 2 dates

Leave tracking application often required to calculate number of days between the range of leave dates. To calucalte the actual leave days we exclude weekends and any holidays comming between the date range. Following code take care of both weekends and Public Holidays —

<script>
var monthNames = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5, jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};

// List of Holiday (Exclude the holdiays that are comming on weekends --)
var holidays = ['01-Jan-2019','04-Mar-2019', '21-Mar-2019', '28-Oct-2019','29-Oct-2019'];


function workingDaysBetweenDates(stDate, enDate) {
    var startDate = parseDate_ddMMMyyy(stDate);
    var endDate = parseDate_ddMMMyyy(enDate);  
    if (endDate < startDate) { return -1; } 
    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 between 
    var weeks = Math.floor(days / 7); 
    days -= weeks * 2; 
    // Handle special cases
    var startDay = startDate.getDay(); 
    var endDay = endDate.getDay(); 
    // Remove weekend not previously removed. 
    if (startDay - endDay > 1) {
        days -= 2;
    }

    // Remove start day if span starts on Sunday but ends before Saturday
    if (startDay == 0 && endDay != 6) {
        days--;  
    }

    // Remove end day if span ends on Saturday but starts after Sunday
    if (endDay == 6 && startDay != 0) {
        days--;
    }
    

    //    Check for Holiday in range -- 
    for (var i in holidays) {
        if ((getDiffDay(holidays[i], startDate) >= 0) && ( getDiffDay(holidays[i] , endDate) <= 0 )) {
            days--;
        }
    }
    return days;
}

// Parse Javascript Date in dd-MMM-yyyy format
function parseDate_ddMMMyyy(s) {
    var p = s.split('-');
    var dt = new Date(p[2], monthNames[p[1].toLowerCase()], p[0]);
    dt.setHours(0,0,0,0);
    return dt;
}

// Get difference between two dates in days 
var dayMilli = 8.64e+7;
function getDiffDay(dt1, dt2) {
    dt1.setHours(0,0,0,0);
    dt2.setHours(0,0,0,0);
    var diff = dt1.getTime() - dt2.getTime();
    return diff / dayMilli;
}

alert("Working days between 01-Jan-2019 to 07-Jan-2019 is = " + workingDaysBetweenDates("01-Jan-2019", "07-Jan-2019"));
</script>

Sample Output

Variable holidays defines all the public holiday for year. If your date if falling beyond current year add all the holidays for falling year also.

Tags: Tags:

by , on January 3rd, 2019