检查日期对象是否超过一年

时间:2015-10-02 19:48:57

标签: javascript

我想看看日期对象是否超过一年!由于闰年等原因,我不知道如何比较它们。

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!");
}

3 个答案:

答案 0 :(得分:0)

您可以像这样进行检查

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

您可以在此处查看并尝试:

https://jsfiddle.net/rnyxzLc2/

答案 1 :(得分:0)

此代码应正确处理闰年。

本质:

如果日期'getFullYear()之间的差异超过一,则 或者差异等于一个 todayDate在将年份设置为相同后大于oldDate
然后有一年以上的差异。

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

答案 2 :(得分:-1)

使用getFullYear()

小提琴: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!");
}