3

I would like to see if a date object is over one year old! I don't know how to even compare them due to the leap years etc..

var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();

if(???) {
    console.log("it has been over one year!");
} else {
    console.log("it has not gone one year yet!");
}
basickarl
  • 37,187
  • 64
  • 214
  • 335
  • Possible duplicate of [Difference between dates in JavaScript](http://stackoverflow.com/questions/1968167/difference-between-dates-in-javascript) – Paul Roub Oct 02 '15 at 20:00
  • Note [this answer](http://stackoverflow.com/a/2400624/1324) which specifically shows how to alert when the difference is > 365 days. – Paul Roub Oct 02 '15 at 20:00

3 Answers3

5

You could make the check like this

(todayDate - oldDate) / (1000 * 3600 * 24 * 365) > 1

You can see and try it here:

https://jsfiddle.net/rnyxzLc2/

Esteban Filardi
  • 726
  • 3
  • 16
  • 30
1

This code should handle leap years correctly.

Essentially:

If the difference between the dates' getFullYear() is more than one,
or the difference equals one and todayDate is greater than oldDate after setting their years to be the same,
then there's more than a one-year difference.

var oldDate = new Date("Oct 2, 2014 01:15:23"),
    todayDate = new Date(),
    y1= oldDate.getFullYear(),
    y2= todayDate.getFullYear(),
    d1= new Date(oldDate).setFullYear(2000),
    d2= new Date(todayDate).setFullYear(2000);

console.log(y2 - y1 > 1 || (y2 - y1 == 1 && d2 > d1));
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
-1

use getFullYear():

fiddle: https://jsfiddle.net/husgce6w/

var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();
var thisYear = todayDate.getFullYear();
var thatYear = oldDate.getFullYear();
console.log(todayDate);
console.log(thatYear);

if(thisYear - thatYear > 1) {
    console.log("it has been over one year!");
} else {
    console.log("it has not gone one year yet!");
}
Jesse
  • 1,262
  • 1
  • 9
  • 19
  • 2
    This would return true for dates that are only one day apart, in the case of 12/31/2015 vs 1/1/2016 – Will P. Oct 02 '15 at 19:53