'How to get time zone offset from IANA time zone code in JavaScript?

I have IANA time zone code like "Asia/Kolkata" and I need to get time zone offset like -330 in JavaScript. I am not able to get time zone offset any help will be appriciated.



Solution 1:[1]

I figured it out how to get time zone offset from IANA time zone code in javascript. I have used moment-timezone-with-data.js as below

var zone = moment.tz.zone('Asia/Kolkata');
zone.parse(Date.UTC(2012, 2, 19, 8, 30)); // -330

Solution 2:[2]

Using the native Date.toLocaleString API:

function timeZoneOffsetInMinutes(ianaTimeZone) {
  const now = new Date();
  now.setSeconds(0, 0);

  // Format current time in `ianaTimeZone` as `M/DD/YYYY, HH:MM:SS`:
  const tzDateString = now.toLocaleString('en-US', {
    timeZone: ianaTimeZone,
    hourCycle: 'h23',
  });

  // Parse formatted date string:
  const match = /(\d+)\/(\d+)\/(\d+), (\d+):(\d+)/.exec(tzDateString);
  const [_, month, day, year, hour, min] = match.map(Number);

  // Change date string's time zone to UTC and get timestamp:
  const tzTime = Date.UTC(year, month - 1, day, hour, min);

  // Return the offset between UTC and target time zone:
  return Math.floor((tzTime - now.getTime()) / (1000 * 60));
}

Solution 3:[3]

I just want to take advantage of your question and promote moment.js which is a great date/time library which supportedny feature I ever needed. For example see:

moment().tz("Asia/Kolkata").offset(...)

For timezones

Solution 4:[4]

You can do this using dayjs, which is a good alternative to the deprecated moment library

import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
dayjs.extend(utc)
dayjs.extend(timezone)

dayjs.tz(undefined, 'Asia/Kolkata').format('ZZ')

Solution 5:[5]

This can be done using the tzdb library, which promises to be kept up-to-date with the IANA database.

const kolkataTimeZone = timeZones.find( ({name}) => name === 'Asia/Kolkata' );
console.log(kolkataTimeZone.rawOffsetInMinutes); // 330

Note that, unlike the deprecated moment.js library, offsets are logically signed, i.e. time zones behind UTC (mainly the Americas) are negative and time zones ahead of UTC (the majority of the world population) are positive.

Solution 6:[6]

Also you can do it with Luxon

import { DateTime } from 'luxon'
    
export function getOffsetFromIANATimezone (ianaTimezone: string): number {
  const dt =DateTime.now().setZone(ianaTimezone)
  return (dt.offset / 60)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shb
Solution 2
Solution 3 akiva
Solution 4
Solution 5 Michael Scheper
Solution 6 Gábor Marosi