I have requirement as follows
I have two dates i need to find how may saturdays and sundays will come in between
Date1: 02/06/2011
Date2: 02/07/2011
10 days are weekends
Thanks
Srini
To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.
To find the first Monday, subtract one from the start date (to cover for starting on Monday). Then find the next Monday.
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.
O(1) solution with no loops:
function countWeekendDays( d0, d1 )
{
var ndays = 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
var nsaturdays = Math.floor( (d0.getDay()+ndays) / 7 );
return 2*nsaturdays + (d0.getDay()==0) - (d1.getDay()==6);
}
jsFiddle
Edited to count number of weekend days instead of number of weekends. http://jsfiddle.net/bRgUq/3/
function CalculateWeekendDays(fromDate, toDate){
var weekendDayCount = 0;
while(fromDate < toDate){
fromDate.setDate(fromDate.getDate() + 1);
if(fromDate.getDay() === 0 || fromDate.getDay() == 6){
++weekendDayCount ;
}
}
return weekendDayCount ;
}
console.log(CalculateWeekendDays(new Date(2011, 6, 2), new Date(2011, 7, 2)));
According to your dates, they are not in US format (at least not if there are 10 weekend days between them). You can get them in US format with something such as...
var chunks = str.split('/');
str = [chunks[1], chunks[0], chunks[2]].join('/');
This code loops through each day between the dates and increments a counter if the day is a Saturday or Sunday.
var start = new Date('06/02/2011'),
finish = new Date('07/02/2011'),
dayMilliseconds = 1000 * 60 * 60 * 24;
var weekendDays = 0;
while (start <= finish) {
var day = start.getDay()
if (day == 0 || day == 6) {
weekendDays++;
}
start = new Date(+start + dayMilliseconds);
}
jsFiddle.
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