0

I am currently trying to compare the launch_date with today's date. Let's say if the launch_date is within 3 years from today's date, it should perform something but I only managed to come out with some portion of the code:

var today = new Date();
var launch_date = 2011/10/17 00:00:00 UTC;
//if today's date minus launch_date is within 3 years, then do something.

Any guides? Thanks in advance.

4 Answers4

0

Try-

var today = new Date();
var launch_date = new Date("2011/10/17 00:00:00 UTC");
var diff = today.getYear() - launch_date.getYear();

if(diff <=3 )
    alert("yes");
else
    alert("no");

jsFiddle

Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
  • But what I am trying to do is if the launch_date is within 3 years from today, then perform something. I am stuck at the point where how to determine if the launch_date is within 3 year from today –  Mar 26 '14 at 07:31
0

To explicitly check for the three year range

var ld = new Date('2011/10/17 00:00:00 UTC') if(today.getFullYear() - ld.getFullYear() < 3) { //do something }

This will fail on an invalid date string and possibly some other edge cases. If you'll be doing a lot of date calculations I highly recommend Moment: http://momentjs.com/

ioseph
  • 1,887
  • 20
  • 25
0

you could always calculate the timespan in days and use that.

var getDays = function(startDate, endDate){
   var ONE_DAY = 1000 * 60 * 60 * 24;
   var difference = endDate.getTime() - startDate.getTime();
   return Math.round(difference / ONE_DAY);
}

See this JsFiddle: http://jsfiddle.net/bj4Dq/1/

Anders Nygaard
  • 5,433
  • 2
  • 21
  • 30
0

you can create a Date object and invoke getTime() method (returns numer of milliseconds since 1970-01-01). Use one of this rows:

var yourDate = new Date(dateString)  // format  yyyy-mm-dd hh:mm:ss
var yourDate = new Date(year, month, day, hours, minutes, seconds, milliseconds)

After in the if statement use this condition:

var edgeDate =  // new Date(dateString);
if ( (today.getTime () - yourDate.getTime ()) >= edgeDate.getTime() ){
    // do something
}

Regards, Kevin

kevinoo
  • 117
  • 10