将具有时区的unix时间戳转换为javascript日期 [英] Convert unix timestamp with a timezone to javascript date
问题描述
我有一个旧版网络应用程序,将日期存储为UNIX时间戳记(自1970年代以来的几秒钟)。通常这样的时间戳表示UTC,但是这些时间戳是UTC-8。它看起来不像日光节约时间(DST)。我可以将它在服务器上转换为UTC并发送给客户端,但是我想知道是否有一个只有javascript的解决方案。
I have a legacy web app that stores dates as a UNIX timestamp (seconds since the epoch 1970). Usually a timestamp like this represents UTC, however these timestamps are UTC-8. It doesn't look like it ever accounts for Daylight Savings Time (DST). I could convert it on the server to UTC and send to the client, but I would like to know if there is a javascript only solution.
示例输入:
1399335987
示例输出:
"2014-05-05T16:26:27-07:00" // Pacific Daylight Time (PDT)
客户端应根据本地计算机显示日期/时间。我研究了使用 momentjs ,但是我找不到如何从数字构造一个日期,而没有数字是UTC。这是可能的吗?
The client should display the date/time according to their local machine. I looked into using momentjs but I could not find how to construct a date from a number without the number being UTC already. Is this possible?
推荐答案
是的,可以给出unix时间戳是UTC,其中时刻时区( http://momentjs.com / timezone / )
Yes, it's possible given the unix timestamps are in UTC, with Moment Timezone (http://momentjs.com/timezone/)
moment
.unix(1399335987)
.tz('MST')
.format('YYYY-MM-DDTHH:mm:ssZ');
你得到
"2014-05-05T17:26:27-07:00"
请注意,我使用 MST
,您应该能够使用任何时区,通过时区数据生成器( http://momentjs.com/timezone/ data / )
Note here I'm using MST
, and you should be able to use whatever timezone you want, via Timezone Data Builder (http://momentjs.com/timezone/data/)
实际上,默认情况下,本地时间将解析并显示。
Actually, by default, moment parses and displays in local time.
这意味着,只有当您处于不同的时区(实际偏移),并且仍然希望在MST中获取本地时间时,则必须将时区设置为MST。
This means, only if you're in a different timezone (offset really) and still want to get the local time in MST, it's necessary to set the timezone as MST.
否则, moment.unix(1399335987).format('YYYY-MM-DDTHH:mm:ssZ')
很好去。
这篇关于将具有时区的unix时间戳转换为javascript日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!