Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine number Saturdays and Sundays comes between two dates in java script

Tags:

javascript

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

like image 500
Srini Avatar asked Jun 02 '11 05:06

Srini


People also ask

How do you find the number of days between two dates?

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.

How can I get Mondays between two dates?

To find the first Monday, subtract one from the start date (to cover for starting on Monday). Then find the next Monday.

How do you find the day difference between two dates excluding weekend days with Javascript?

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.


3 Answers

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

like image 104
Matt Avatar answered Nov 14 '22 23:11

Matt


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)));
like image 42
Brett Avatar answered Nov 14 '22 23:11

Brett


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.

like image 37
alex Avatar answered Nov 14 '22 23:11

alex