Search code examples
javascriptdatetimeinternationalization

Timezone offset by timezone name for a specific date in Javascript


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.


Solution

  • 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