gpt4 book ai didi

javascript:计算两个日期之间的差异

转载 作者:行者123 更新时间:2023-12-04 00:40:27 25 4
gpt4 key购买 nike

我想找出两个日期之间的差异。为此,我确实从另一个 Date 对象中减去一个 Date 对象。我的代码如下:

var d1 = new Date(); //"now"
var d2 = new Date(2012,3,17); // before one year
document.write("</br>Currrent date : "+d1);
document.write("</br>Other Date : "+d2);
document.write("</br>Difference : "+new Date(Math.abs(d1-d2)));

但结果并不如我所料:

当前日期:2013 年 2 月 17 日星期日 02:58:16 GMT-0500 (EST)
其他日期:2012 年 1 月 21 日星期六 00:00:00 GMT-0500 (EST)
差异:1971 年 1 月 28 日星期四 21:58:16 GMT-0500 (EST)

我想计算它们之间的(1 年)差异。

谢谢

最佳答案

因此,从根本上说,最大的确切日期单位是 ,它占 7 * 86400 秒。月份和年份没有明确定义。所以假设你想说“1 个月前”,如果这两个日期是5.1.20135.2.20135.2.20135.3.2013。并说“1 个月零 1 天前”,如果你有,例如5.1.20136.2.2013,那么您将不得不使用这样的计算:

// dateFrom and dateTo have to be "Date" instances, and to has to be later/bigger than from.
function dateDiff(dateFrom, dateTo) {
var from = {
d: dateFrom.getDate(),
m: dateFrom.getMonth() + 1,
y: dateFrom.getFullYear()
};

var to = {
d: dateTo.getDate(),
m: dateTo.getMonth() + 1,
y: dateTo.getFullYear()
};

var daysFebruary = to.y % 4 != 0 || (to.y % 100 == 0 && to.y % 400 != 0)? 28 : 29;
var daysInMonths = [0, 31, daysFebruary, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

if (to.d < from.d) {
to.d += daysInMonths[parseInt(to.m)];
from.m += 1;
}
if (to.m < from.m) {
to.m += 12;
from.y += 1;
}

return {
days: to.d - from.d,
months: to.m - from.m,
years: to.y - from.y
};
}
// Difference from 1 June 2016 to now
console.log(dateDiff(new Date(2016,5,1), new Date()));

正如我所说,它变得棘手 ;)

关于javascript:计算两个日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14919201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com