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
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.
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.