Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if date object is over one year old

Tags:

javascript

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!");
}
like image 443
basickarl Avatar asked Oct 30 '25 10:10

basickarl


2 Answers

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/

like image 114
Esteban Filardi Avatar answered Nov 02 '25 00:11

Esteban Filardi


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));
like image 20
Rick Hitchcock Avatar answered Nov 01 '25 22:11

Rick Hitchcock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!