Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of sundays between two dates

Tags:

javascript

I tried the JS below:

var start = new Date("25-05-2016");
var finish = new Date("31-05-2016");
var dayMilliseconds = 1000 * 60 * 60 * 24;
var weekendDays = 0;
while (start <= finish) {
  var day = start.getDay()
  if (day == 0) {
    weekendDays++;
  }
  start = new Date(+start + dayMilliseconds);
}
alert(weekendDays);

However, it gives the wrong output.

I need to get the total count of Sundays between the two dates.

like image 583
vishuB Avatar asked May 24 '16 07:05

vishuB


People also ask

How do you calculate weekends between two dates?

To do this you have to add the Days Between to the Day of the Week, and then FLOOR that value to get the highest integer result. You then divide that number by 7 to get the amount of WEEKS and then multiply that by 2 to calculate the amount of WeekEnd days. Name this calculation "Weekend days".

How do I calculate the number of days between two dates in Excel excluding Sundays?

Count days excluding Sundays with formula Select a blank cell, here is C2, and type this formula =B2-A2-INT((B2-A2-WEEKDAY(B2)+1)/7) into it, and then press Enter key, a date displayed.

How do I count the number of weekends between two dates in Excel?

We can use the NETWORKDAYS function to calculate the number of weekends between two dates. While the Networkdays function calculates the number of working days, we can also use to get the number of weekend days between two dates.

How do I get Sundays between two dates in Python?

TotalDays / 7) + (sdate. DayOfWeek == DayOfWeek. Sunday || fdate. DayOfWeek == DayOfWeek.


1 Answers

Your date format is wrong. Dates' string format is "yyyy-mm-dd". See here for more information.

Also, looping each day of the interval is very inefficient. You may try the following instead.

function getNumberOfWeekDays(start, end, dayNum){
  // Sunday's num is 0 with Date.prototype.getDay.
  dayNum = dayNum || 0;
  // Calculate the number of days between start and end.
  var daysInInterval = Math.ceil((end.getTime() - start.getTime()) / (1000 * 3600 * 24));
  // Calculate the nb of days before the next target day (e.g. next Sunday after start).
  var toNextTargetDay = (7 + dayNum - start.getDay()) % 7;
  // Calculate the number of days from the first target day to the end.
  var daysFromFirstTargetDay = Math.max(daysInInterval - toNextTargetDay, 0);
  // Calculate the number of weeks (even partial) from the first target day to the end.
  return Math.ceil(daysFromFirstTargetDay / 7);
}


var start = new Date("2016-05-25");
var finish = new Date("2016-05-31");

console.log("Start:", start);
console.log("Start's week day num:", start.getDay());
console.log("Finish:", finish);
console.log("Finish's week day num:", finish.getDay());

console.log("Number of Sundays:", getNumberOfWeekDays(start, finish));
like image 160
Quentin Roy Avatar answered Nov 14 '22 22:11

Quentin Roy