本文介绍了将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纪元var存储在几秒钟内。怎么样 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转换为本地日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 23:11