【发布时间】:2022-12-07 18:13:53
【问题描述】:
有一个接受日期并进行一些处理的 API 端点。我确实通过邮递员将日期作为 UTC(末尾用 Z 表示)。从 Postman 发送的示例输入。
{
"experimentDate":"2022-01-12T12:30:00.677Z",
}
在我做的代码中
let startDate = new Date(experimentDate);
//other calculations e.g get midnight of the startDate
startDate.setHours(0,0,0,0);
第一个任务将 startDate 设置为更正为当前时区。因此,我的其余计算都变坏了。例如,当我使用 setHours 函数将时间设置为 0 时,我希望它在给定的 UTC 时间的午夜,但它会进入我当前时区的午夜。 鉴于日期末尾有 Z,新日期是否应该不保留 UTC 日期?
我应该像下面那样将它重新转换为 UTC 吗?这不是多余的吗?
let startDate = new Date(experimentDate);
Date.UTC(startDate.getUTCFullYear(), startDate.getUTCMonth(),
startDate.getUTCDate(), startDate.getUTCHours(),
startDate.getUTCMinutes(), startDate.getUTCSeconds())
//other calculations e.g get midnight of the startDate
startDate.setHours(0,0,0,0);
实现这一目标的正确方法是什么?
【问题讨论】:
-
您可以使用
.setUTCHours()而不是.setHours()
标签: javascript node.js typescript