How can I find timezone offset in hours or minutes using timezone name for a specific date.
Example use would be :
var offset = findOffset("America/New_York", new Date(2019,08,07))
// offset is -4
I am hoping to find a solution using native JS, but if it does not exist I am also ok with using some libraries.
I will recommend Moment Timezone which is a JS library and it is quite popular (3,660,521 weeks NPM downloads). Moment and Moment Timezone are sibling libraries (Same developer).
The moment timezone library gives you offset in the output like shown below:
moment.tz("2013-12-01", "America/Los_Angeles").format(); // 2013-12-01T00:00:00-08:00
moment.tz("2013-06-01", "America/Los_Angeles").format(); // 2013-06-01T00:00:00-07:00
So here is the answer I found
const findTimeZoneOffset = (tz,date) => {
let utcDate = new Date(date.toLocaleString('en-US', { timeZone: "UTC" }));
let tzDate = new Date(date.toLocaleString('en-US', { timeZone: tz }));
let diff = ( tzDate.getTime() - utcDate.getTime() ) / 1000 / 60 / 60;
return diff;
};
and as expected
findTimeZoneOffset("America/New_York", new Date(2019,08,07))
// returns -4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.