8

Possible Duplicate:
Get difference between 2 dates in javascript?

I am storing date variables like this:

var startYear = 2011;
var startMonth = 2;
var startDay = 14;

Now I want to check if current day (today) is falling within 30 days of the start date or not. Can I do this?

var todayDate = new Date();
var startDate = new Date(startYear, startMonth, startDay+1);
var difference = todayDate - startDate;

????

I am not sure if this is syntactically or logically correct.

Community
  • 1
  • 1
ssdesign
  • 2,743
  • 6
  • 37
  • 53

2 Answers2

25

In JavaScript, the best way to get the timespan between two dates is to get their "time" value (number of milliseconds since the epoch) and convert that into the desired units. Here is a function to get the number of days between two dates:

var numDaysBetween = function(d1, d2) {
  var diff = Math.abs(d1.getTime() - d2.getTime());
  return diff / (1000 * 60 * 60 * 24);
};

var d1 = new Date(2011, 0, 1); // Jan 1, 2011
var d2 = new Date(2011, 0, 2); // Jan 2, 2011
numDaysBetween(d1, d2); // => 1
var d3 = new Date(2010, 0, 1); // Jan 1, 2010
numDaysBetween(d1, d3); // => 365
maerics
  • 151,642
  • 46
  • 269
  • 291
  • I tried this: http://pastie.org/1981365 but it always gives me positive integer... i would like to know if current date is before or after... – ssdesign May 27 '11 at 16:05
  • @ssdesign: your code should return a negative integer if the start date is before today; my code can be modified for that effect by removing the `Math.abs` around the subtraction. – maerics May 27 '11 at 16:12
2
(todayDate.getTime() - startDate.getTime())/(1000*60*60*24.0)
Razor Storm
  • 12,167
  • 20
  • 88
  • 148