How do I find the number of days between two dates in javascript?

advertisements

This question already has an answer here:

  • How do I get the number of days between two dates in JavaScript? 28 answers

I have two arbitrary dates, lets say April 1st 2012 and January 15th 2013. I want to calculate the number of Sundays, Mondays, Tuesdays, Wednesdays, Thursdays, Fridays, and Saturdays between those two dates.

Is there a surefire-quick way to do this without crippling the users CPU/browser?

Thanks

Update

The premise of this is, we have a defined average number of events for any given day of the week. We need to calculate the number of events to happen in a time period, even for partials (like 1/2 day of Sunday would be half the number of events added to total)


Ok, here is a possible untested solution

date1 = new Date("2012-02-10");
date2 = new Date("2012-03-10");

daysInBetween = (date2.getTime() - date1.getTime())/1000/3600/24;

dayOfTheWeek1 = date1.getDay();

weeks = parseInt(daysInBetween/7, 10);
extraDays = daysInBetween%7;

You have weeks + 1 days of dayOfWeek1 ... dayOfWeek1 + (6 - extraDays)

You have weeks + 1 + extraDays days of dayOfWeek1 + (6 - extraDays) ... dayOfWeek1 + 6

Please take into acount that if dayOfWeek1 === 6 then I am assuming that dayOfWeek1 + 1 === 0.

EDIT:

A little bit more of code:

var days = {};
var dayOfTheWeekEnd = dayOfTheWeek1 + 6 - extraDays; // no imagination for names...
if (dayOfTheWeekEnd < 6) {
  if (0 >= dayOfTheWeek1 && 0 <= dayOfTheWeekEnd) {
    days.sunday = weeks + 1;
  } else {
    days.sunday = weeks + 1 + extraDays;
  }
  // etc for the other days, a for loog with an i instead of the 0 would be better.
} else {
  // I have to go the school! I'll edit it later.
  // The idea is that you have to take dayOfTheWeekEnd back to the 0-6 range
  // and check if its after dayOfWeek1 or before dayOfTheWeekEnd, then days.sunday=weeks+1.
}