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

标签 javascript date utc milliseconds gmt

我正在尝试将毫秒转换为 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/

相关文章:

html中的javascript点击按钮

javascript - 我如何在每次迭代之间间隔循环中为 DOM 元素设置动画?

javascript - 递归 jQuery 提交函数不提交表单

javascript - 在此代码中将日期格式化为 dd/MM/yyyy

Java:将UTC日期转换为本地时区

mysql - 在数据库中存储不同时区用户的时间

javascript - 如何访问不同的 iframe?

php - strtotime 函数返回 01/01/70 且输入有效

Javascript setMonth 显示不正确的日期

java - 在不使用弃用代码的情况下从 YMD HMS 值创建 Java 日期