首页 > 解决方案 > 节点 JS 日期对象在夏令时前后表现异常

问题描述

所以我正在做一个更大的项目,我遇到了一个错误,我想看看我可能做错了什么。我遍历大量数据并四舍五入一些日期以将我的输出清理到 15 分钟的存储桶中。

代码:

//how I've been doing things
let expectedBehvaior = new Date("2020-11-01T05:14:00.000Z");
console.log(expectedBehvaior.toISOString());
expectedBehvaior.setMinutes(0);
console.log(expectedBehvaior.toISOString());

//using set minutes creates an issue for only hours 6 UTC on Nov 1st 2020
let crazyDate = new Date("2020-11-01T06:14:00.000Z");
console.log(crazyDate.toISOString());
crazyDate.setMinutes(0);
console.log(crazyDate.toISOString());

//how i fixed it
let fixedDate = new Date("2020-11-01T06:14:00.000Z");
console.log(fixedDate.toISOString());
fixedDate.setTime(fixedDate.getTime() - 60000 * fixedDate.getMinutes());
console.log(fixedDate.toISOString());

输出:

2020-11-01T05:14:00.000Z
2020-11-01T05:00:00.000Z
2020-11-01T06:14:00.000Z
2020-11-01T05:00:00.000Z
2020-11-01T06:14:00.000Z
2020-11-01T06:00:00.000Z

这似乎与美国的夏令时有关,因为同样的事情发生在 2019 年 11 月 3 日。不确定 Date.setMinutes 在后台如何工作,并希望有人能解释这种行为。

谢谢你。

编辑:

在我调用 crazyDate.setMinutes(0) 之后,我希望小时保持不变。相反,它将它设置回 0500 UTC,而不是 0600 UTC。

标签: javascriptnode.jsdst

解决方案


推荐阅读