如何将 unix 时间戳转换为 JavaScript 日期对象(考虑时区)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11656601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:55:17  来源:igfitidea点击:

How to convert unix timestamp to JavaScript date object (consider time zone)

javascriptdate

提问by sozhen

var date = new Date(1257397200000?);
document.write(date);
?

Ran the code above I got Wed Nov 04 2009 23:00:00 GMT-0600 (Central Standard Time)

运行上面的代码我得到 Wed Nov 04 2009 23:00:00 GMT-0600 (Central Standard Time)

I am looking for a way to create date object based on different time zone, say for that time stamp I want to obtain date object like Thursday, November 5th 2009, 00:00:00 (GMT -5).

我正在寻找一种方法来创建基于不同时区的日期对象,比如说我想获取像Thursday, November 5th 2009, 00:00:00 (GMT -5).

Note that the dates are different according to above two time zones, though they represent same point in time. I am in CST, is that why the created object is generated using CST?

请注意,尽管它们代表相同的时间点根据上述两个时区的日期不同。我在 CST 中,这就是为什么使用 CST 生成创建的对象的原因吗?

Thank you.

谢谢你。

回答by Tomasz Nurkiewicz

No, these dates aren't different as they don't represent different point in time. The both represent Thu, 05 Nov 2009 05:00:00 GMT.

不,这些日期没有什么不同,因为它们不代表不同的时间点。两者都代表Thu, 05 Nov 2009 05:00:00 GMT

Dateobject in JavaScript is time-zone independent, it only represents point in time. The fact that Date.toString()includes time zone is very misleading, there is no time-zone information in Date. It is only a wrapper around milliseconds since epoch.

DateJavaScript 中的对象与时区无关,它只代表时间点。Date.toString()包含时区这一事实非常具有误导性,.NET 中没有时区信息Date。自纪元以来,它只是一个大约毫秒的包装器。

The time zone you see is based on OS/browser locale. You cannot create Dateobject in different time-zone. Consider using getUTC*()family of methods to get browser time-zone agnostic values.

您看到的时区基于操作系统/浏览器区域设置。您不能Date在不同的时区创建对象。考虑使用getUTC*()一系列方法来获取浏览器时区不可知值。

BTW your example code prints:

顺便说一句,您的示例代码打印:

Thu Nov 05 2009 06:00:00 GMT+0100 (CET)

on my computer - and this is still the same point in time.

在我的电脑上 - 这仍然是同一个时间点。

See also

也可以看看