使用javascript将UTC时代转换为本地日期 [英] Convert UTC Epoch to local date with javascript

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

问题描述

我已经和这个战斗了一段时间了。我试图将纪元转换为日期对象。时代以UTC发送给我。每当你通过 new Date()一个时期,它假定它是本地时代。我尝试创建一个UTC对象,然后使用setTime()来调整它到正确的时代,但唯一的方法似乎很有用的是 toUTCString()和字符串没有帮助我。如果我将该字符串传递到一个新的日期,应该注意到它是UTC,但它不是

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

我的下一次尝试是尝试获取本地当前时代与utc当前时代之间的区别,但是我也无法得到这一点。

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

只给我非常小的差异,小于1000,这是毫秒。



任何建议?

解决方案

我想我有一个更简单的解决方案 - 将初始日期设置为纪元,并添加UTC单位。说你有一个UTC时代var存储在几秒钟内。如何 1234567890 。要将其转换为当地时区的正确日期:

  var utcSeconds = 1234567890; 
var d = new Date(0); // 0是有关键,它将日期设置为epoch
d.setUTCSeconds(utcSeconds);

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


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()

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()

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

Any suggestions?

解决方案

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

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

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