Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  127] [ 2]  / answers: 1 / hits: 24774  / 13 Years ago, fri, may 27, 2011, 12:00:00

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.


More From » date

 Answers
11

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

[#92018] Wednesday, May 25, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lonnier

Total Points: 621
Total Questions: 113
Total Answers: 98

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;