我希望有人能在这方面帮助我...
我有这个功能,它按预期工作。它检查闰年,相应地需要 365 或 366 天。
问题:我想检查 fromdate 和 todate,而不是检查闰年,如果这些日期中的任何一个从 2 月 29 日开始并且 fromdate 和 todate 之间的差异超过 365,然后添加 +1 到 daysInYear,否则只考虑 365 天。我不会在给定的开始日期和日期中有任何 2 闰年的时期。所以我不担心这种情况。希望清楚。
getDifference: function(fromdate,toDate) {
var now = toDate || new Date();
// days since the date
var days = Math.floor((fromdate.getTime() - now.getTime())/1000/60/60/24);
var diff = 0;
// iterate the years
for (var y = now.getFullYear(); y <= fromdate.getFullYear(); y++){
var daysInYear = opc.calculator.leapYear(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
diff++;
// increment the age only if there are available enough days for the year.
}
}
return diff;
}
如果您
不介意在代码中添加库,请查看:Moment.js
你做这样的事情:
moment().diff(moment('20140229', 'YYYYMMDD'), 'days');
// returns 417 today (2015-04-22)
// or
moment('20150422', 'YYYYMMDD').diff(moment('20140229', 'YYYYMMDD'), 'days');
这是一个处理时间和日期的好库。