I'm trying to get the working days between two date. Example: stdate = 28/10/2011 and endate = 04/11/2011. This should be 6 working days, but its only giving 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 twice for some reason. Any help would be appreciated.
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 indication for the two variables is zero based. So in my example we are looking at october (month 10).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With