admin管理员组

文章数量:1318572

I would like to see if a date object is over one year old! I don't know how to even pare 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!");
}

I would like to see if a date object is over one year old! I don't know how to even pare 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!");
}
Share Improve this question asked Oct 2, 2015 at 19:48 basickarlbasickarl 40.6k69 gold badges238 silver badges355 bronze badges 2
  • Possible duplicate of Difference between dates in JavaScript – Paul Roub Commented Oct 2, 2015 at 20:00
  • Note this answer which specifically shows how to alert when the difference is > 365 days. – Paul Roub Commented Oct 2, 2015 at 20:00
Add a ment  | 

3 Answers 3

Reset to default 6

You could make the check like this

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

You can see and try it here:

https://jsfiddle/rnyxzLc2/

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));

use getFullYear():

fiddle: https://jsfiddle/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!");
}

本文标签: javascriptCheck if date object is over one year oldStack Overflow