2017-08-08 480 views
1

我有一个UTC日期时间字符串和时区名称。我从第三方API获取此信息。我需要使用JavaScript/NodeJS将UTC时间转换为该时区的本地时间,并获取该时区的当前时间。有没有相同的图书馆/方法?JavaScript:使用时区将UTC时间转换为本地时间

var timezone = "America/New_York";//This will always be in Olson format. 
var UTCTime = "2017-09-03T02:00:00Z"; 
var localTime; //I need to find the equivalent of UTCTime for America/New_York 
var currentTime; //Current time of time zone America/New_York 
+0

有用的资源https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date – Atiq

+0

时刻(http://momentjs.com/docs/)是一个非常强大和流行的日期操作库,很可能你的需求可以被它覆盖。 – tibetty

回答

0

这可以通过几种方式来完成:

var options = { 
    timeZone: "America/New_York", 
    year: 'numeric', month: 'numeric', day: 'numeric', 
    hour: 'numeric', minute: 'numeric', second: 'numeric' 
}; 

var formatter = new Intl.DateTimeFormat([], options); 

var UTCTime = "2017-09-03T02:00:00Z"; 
var localTime = formatter.format(new Date(UTCTime)); 
var currentTime = formatter.format(new Date()); console.log(currentTime, localTime); 

或者您可以使用moment.js库。

0

您可以使用getTimezoneOffset(),以分钟为单位返回偏移量。然后你可以修改你的日期到相应的函数返回。

你可能也想看看moment.js这是一个非常有用的图书馆,当谈到javascipt日期。

相关问题