Getting working days with Javascript

I am trying to get working days between two dates. Example: stdate = 10/28/2011 and endate = 04/11/2011. It should be 6 business days, but only for 5 days.

var workingdays = 0; var weekday = new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; while (stdate <= endate) { var day = weekday[stdate.getDay()]; if(day != "Saturday" && day != "Sunday") { workingdays++; } console.log(weekday[stdate.getDay()]); stdate = new Date(stdate.getTime() + 86400000); } 

The console log shows the results below.

 Friday Saturday Sunday Sunday Monday Tuesday Wednesday Thursday 

Sunday shows for some reason twice. Any help would be appreciated.

+6
source share
4 answers

Summer time.

As you add 24 hours to the date, this is not enough to deliver you the next day on Sunday, since there is 25 hours on this special Sunday.

You should add a day instead of adding hours:

 stdate = new Date(stdate.getFullYear(), stdate.getMonth(), stdate.getDate() + 1); 

Explanation: When you call the Date constructor with a date that is outside the valid range, it is automatically carried over to the next month, i.e. new Date(2010,9,32) gives you the first of November.

+6
source

Here you go:

  function getWorkingDays(startDate, endDate){ var result = 0; var currentDate = startDate; while (currentDate <= endDate) { var weekDay = currentDate.getDay(); if(weekDay != 0 && weekDay != 6) result++; currentDate.setDate(currentDate.getDate()+1); } return result; } var begin = new Date(2011, 09, 8); var end = new Date(2011, 09, 25); alert(getWorkingDays(begin, end)); // result = 12 days 

Keep in mind that the month display for two variables is based on a zero value. Therefore, in my example, we look at October (the 10th month).

+7
source

You can try this

 stdate.setDate(stdate.getDate()+1); 

instead

 stdate = new Date(stdate.getTime() + 86400000); 
+2
source

You can get the date of the week from StartDate and EndDate

 var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var object = []; function getTuesday(startDate, endDate, n) { var currentDate = startDate; while (currentDate <= endDate) { if (weekday[currentDate.getDay()] === weekday[n]) object.push(currentDate + "\n"); currentDate.setDate(currentDate.getDate() + 1); } return object; } var begin = new Date(2015, 11, 08); var end = new Date(2016, 01, 08); alert(getTuesday(begin, end, 3) + "\n Total date or week: " + object.length); 
0
source

Source: https://habr.com/ru/post/900420/


All Articles