将 UTC Epoch 转换为本地日期 [英] Convert UTC Epoch to local date

查看:40
本文介绍了将 UTC Epoch 转换为本地日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为此抗争了一段时间.我正在尝试将纪元转换为日期对象.时代以UTC格式发送给我.每当您向 new Date() 传递一个纪元时,它就会假定它是本地纪元.我尝试创建一个 UTC 对象,然后使用 setTime() 将其调整到适当的时代,但似乎唯一有用的方法是 toUTCString() 并且字符串没有帮我.如果我将该字符串传递给一个新日期,它应该注意到它是 UTC,但它不是.

I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date() an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using setTime() to adjust it to the proper epoch, but the only method that seems useful is toUTCString() and strings don’t help me. If I pass that string into a new date, it should notice that it’s UTC, but it doesn’t.

new Date( new Date().toUTCString() ).toLocaleString()

我的下一次尝试是尝试获取本地当前纪元和 UTC 当前纪元之间的差异,但我也无法得到.

My next attempt was to try to get the difference between local current epoch and UTC current epoch, but I wasn’t able to get that either.

new Date( new Date().toUTCString() ).getTime() - new Date().getTime()

它只给了我很小的差异,低于 1000,以毫秒为单位.

It’s only giving me very small differences, under 1000, which is in milliseconds.

有什么建议吗?

推荐答案

我想我有一个更简单的解决方案——将初始日期设置为纪元并添加 UTC 单位.假设您有一个以秒为单位存储的 UTC 纪元变量.1234567890怎么样.要将其转换为本地时区中的正确日期:

I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:

var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);

d 现在是一个日期(在我的时区)设置为 2009 年 2 月 13 日星期五 18:31:30 GMT-0500 (EST)

d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)

这篇关于将 UTC Epoch 转换为本地日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆