gpt4 book ai didi

javascript - 将毫秒转换为具有 UTC 时区的 UTC 日期对象

转载 作者:行者123 更新时间:2023-11-30 09:34:31 26 4
gpt4 key购买 nike

我正在尝试将毫秒转换为 UTC 日期对象,如下所示 -

var tempDate = new Date(1465171200000);
// --> tempDate = Mon Jun 06 2016 05:30:00 **GMT+0530 (India Standard Time)** {}

var _utcDate = new Date(tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate(), tempDate.getUTCHours(), tempDate.getUTCMinutes(), tempDate.getUTCSeconds());
//--> _utcDate = Mon Jun 06 2016 00:00:00 **GMT+0530 (India Standard Time)** {}

时间正在重置为 UTC 时间,但时区仍为 GMT+0530(印度标准时间)。是否有可靠的方法可以将毫秒转换为具有 UTC 时区的 UTC 日期对象?

最佳答案

引自 this answer (我建议您完整阅读):

There is no time zone or string format stored in the Date object itself. When various functions of the Date object are used, the computer's local time zone is applied to the internal representation.

由于时区未存储在 Date 对象中,因此无法设置它。

我看到两个选项:

第一个 是使用库(如上面的答案中所建议的)。现在比较流行的是Moment.js

第二个(纯 JavaScript - 如果它在您的上下文中是一个可行的解决方案):

在您本地的时区进行“时间计算”。

当您准备好切换到 UTC 时,请使用 toUTCString() 方法。

当然,您最终会得到一个字符串,因为这样您就可以存储与日期时间值一样长的时区。

因为从现在开始您将无法将日期时间作为 Date 对象进行操作,所以这必须是最后一步。

var tempDate = new Date(1465171200000);
// Mon Jun 06 2016 05:30:00 GMT+0530

// Do your date time math here
// using the Date object's methods

var utcDateAsString = tempDate.toUTCString();
// Mon Jun 06 2016 00:00:00 GMT

关于javascript - 将毫秒转换为具有 UTC 时区的 UTC 日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44389775/

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