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.
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
(todayDate.getTime() - startDate.getTime())/(1000*60*60*24.0)
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