JavaScript: Convert UTC time to local time using timezone [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

This question already has an answer here:

I have a UTC date time string and time zone name. I am getting this from a third party API. I need to convert the UTC time to local time of that timezone using JavaScript/NodeJS as well as get that time zone's current time. Is there any library/method available for the same?

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 

回答1:

This can be done in few ways:

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

Or you can use moment.js library.



回答2:

You could use getTimezoneOffset() which returns the offset in minutes. You can then modify your date to the corresponding return of the function.

You may also want to look at moment.js which is a very useful library when it comes to javascipt dates.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!