Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

javascript - 将UTC Epoch转换为本地日期(Convert UTC Epoch to local date)

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.

(这个时代以UTC的形式发送给我。)

Whenever you pass new Date() an epoch, it assumes it's local epoch.

(每当你传递一个new Date()时代时,它就会假定它是本地时代。)

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.

(我尝试创建一个UTC对象,然后使用setTime()将其调整到正确的纪元,但唯一有用的方法是toUTCString()和字符串对我toUTCString() 。)

If I pass that string into a new date, it should notice that it's UTC, but it doesn't.

(如果我将该字符串传递给新的日期,它应该注意到它是UTC,但事实并非如此。)

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

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.

(我的下一次尝试是尝试获取当地当前时期和UTC当前时期之间的差异,但我也无法得到它。)

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

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

(它只给了我很小的差异,低于1000,这是毫秒。)

Any suggestions?

(有什么建议?)

  ask by Shane Reustle translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think I have a simpler solution -- set the initial date to the epoch and add UTC units.

(我想我有一个更简单的解决方案 - 将初始日期设置为纪元并添加UTC单位。)

Say you have a UTC epoch var stored in seconds.

(假设您有一个UTC纪元var存储在几秒钟内。)

How about 1234567890 .

(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 is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)

(d现在是一个日期(在我的时区)设置为Fri Feb 13 2009 18:31:30 GMT-0500 (EST))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...