JavaScript:使用时区将UTC时间转换为本地时间

我有一个UTCdate时间string和时区名称。 我从第三方API获取这个。 我需要使用JavaScript / NodeJS将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 

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

 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库。

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

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