Get the number of work days between two dates

Document created by AdisJ Employee on Apr 11, 2018
Version 1Show Document
  • View in full screen mode

Very often, in different business apps scenarios, you will need to get the number of work days between two dates. This code snippet will help you to do exactly that. 

 

In order to get the date values from the SharePoint fields (if you are working with New or Edit forms), please take a look at the following document: Reading JavaScript date values from SharePoint date fields regardless of locale (culture)  

 

 

var millisecondsPerDay = 86400 * 1000; // Day in milliseconds

dDate1.setHours(0,0,0,1);  // Start just after midnight
dDate2.setHours(23,59,59,999);  // End just before midnight

var diff = dDate2 - dDate1;  // Milliseconds between datetime objects   
var days = Math.ceil(diff / millisecondsPerDay);

// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);

// Handle special cases
var startDay = dDate1.getDay();
var endDay = dDate2.getDay();

// Remove weekend not previously removed.  
if (startDay - endDay > 1)        
    days = days - 2;     

// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
    days = days - 1l
       
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1 

return days;

Attachments

    Outcomes