Tag Archives: Javascript

Javascript: How to Calculate Number of Working Days?

Date.workingDaysFrom(fromDate) calculates the number of working days between 2 Date objects (excluding weekends; Sat and Sun). The method will return “-1” if the fromDate┬áis an invalid Date object or is later than the compared Date.

Do take note that this method does not take public holidays into consideration and each date is consider as a full day.

Date.prototype.workingDaysFrom=function(fromDate){
 // ensure that the argument is a valid and past date
 if(!fromDate||isNaN(fromDate)||this<fromDate){return -1;}

 // clone date to avoid messing up original date and time
 var frD=new Date(fromDate.getTime()),
     toD=new Date(this.getTime()),
     numOfWorkingDays=1;

 // reset time portion
 frD.setHours(0,0,0,0);
 toD.setHours(0,0,0,0);

 while(frD<toD){
  frD.setDate(frD.getDate()+1);
  var day=frD.getDay();
  if(day!=0&&day!=6){numOfWorkingDays++;}
 }
 return numOfWorkingDays;
};

 

Examples

Comparing 8-Jul-2015 (Wed) to 13-Jul-2015 (Mon)

var startDate = new Date("8/8/2015");
var endDate = new Date("13/8/2015");
endDate.workingDaysFrom(startDate); // returns 4

Comparing same date, 8-Jul-2015 (Wed)

var startDate = new Date("8/8/2015");
var endDate = new Date("8/8/2015");
endDate.workingDaysFrom(startDate); // returns 1