Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if date is within 30 days? [duplicate]

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.

like image 878
ssdesign Avatar asked May 27 '11 15:05

ssdesign


2 Answers

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
like image 137
maerics Avatar answered Sep 28 '22 05:09

maerics


(todayDate.getTime() - startDate.getTime())/(1000*60*60*24.0)
like image 24
Razor Storm Avatar answered Sep 28 '22 06:09

Razor Storm