我想查看一个日期对象是否超过一年的时间!由于闰年等问题,我不知道如何进行比较。
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!");
}
我想查看一个日期对象是否超过一年的时间!由于闰年等问题,我不知道如何进行比较。
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!");
}
(todayDate - oldDate) / (1000 * 3600 * 24 * 365) > 1
这段代码应正确处理闰年。
基本上:
如果两个日期的 getFullYear()
差值大于1,
或者差值等于1并且将它们的年份设为相同后,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));
使用 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!");
}