34

I need a Javascript function that given a timezone, returns the current UTC offset.

For example, theFuncIneed('US/Eastern') -> 240

6
  • Create an object with the timezone names as properties and the offset as value. Note that there is no standard for timezone names, they change from time to time and there are duplicates (e.g. EST).
    – RobG
    Commented Dec 20, 2013 at 21:48
  • Check out moment.js, it has a zone() method.
    – Barmar
    Commented Dec 20, 2013 at 21:50
  • 1
    @MattJohnson—I'm not sure what your point is. IANA provide timezone offsets for particular locations. IANA data isn't a standard or even authoritative and there is no pretence that it is (the header of the data file says "This data is by no means authoritative; if you think you know better, go ahead and edit the file").
    – RobG
    Commented Dec 21, 2013 at 11:54
  • 1
    @RobG - Agreed. The IANA time zone database not a standard in the way that ISO 8601 is a standard. But it's a de facto standard by convention that it's used ubiquitously throughout multiple operating systems, programming languages, and libraries. So while there are no guarantees, it's still highly likely that US/Eastern will be recognized by all implementations. Commented Dec 21, 2013 at 17:45
  • 1
    @MattJohnson—I think this is way off track. My point was to caution that there is no standard for timezone designators. The IANA database includes a number of exceptions for the timezone observed in a place compared to its geographic location and for the start and end of daylight saving where it's contrary to "official" dates.
    – RobG
    Commented Dec 21, 2013 at 21:49

5 Answers 5

17

It has become possible nowaday with Intl API:

The implementation of Intl is based on icu4c. If you dig the source code, you'll find that timezone name differs per locale, for example:

for (const locale of ["ja", "en", "fr"]) {
  const timeZoneName = Intl.DateTimeFormat(locale, {
    timeZoneName: "short",
    timeZone: "Asia/Tokyo",
  })
    .formatToParts()
    .find((i) => i.type === "timeZoneName").value;
  console.log(timeZoneName);
}

Fortunately, there is a locale, Interlingua (the langauge tag is ia), which uses the same pattern (ex. GMT+11:00) for timezone names.

The snippet below can meed your need:

const getOffset = (timeZone) => {
  const timeZoneName = Intl.DateTimeFormat("ia", {
    timeZoneName: "short",
    timeZone,
  })
    .formatToParts()
    .find((i) => i.type === "timeZoneName").value;
  const offset = timeZoneName.slice(3);
  if (!offset) return 0;

  const matchData = offset.match(/([+-])(\d+)(?::(\d+))?/);
  if (!matchData) throw `cannot parse timezone name: ${timeZoneName}`;

  const [, sign, hour, minute] = matchData;
  let result = parseInt(hour) * 60;
  if (sign === "+") result *= -1;
  if (minute) result += parseInt(minute);

  return result;
};

console.log(getOffset("US/Eastern")); // 240
console.log(getOffset("Atlantic/Reykjavik")); // 0
console.log(getOffset("Asia/Tokyo")); // -540

This way can be a little tricky but it works well in my production project. I hope it helps you too :)

Update

Many thanks to Bort for pointing out the typo. I have corrected the snippet.

13
  • 1
    There's a typo at if (minute) result + parseInt(minute);. Should that be +=?
    – Bort
    Commented Nov 3, 2020 at 19:45
  • 1
    This does not work for the values in the example - returns 0 for "US/Eastern" and "Atlantic/Reykjavik"
    – Avraham
    Commented Mar 4, 2021 at 15:54
  • 2
    @kleinfreund Strange, when I run the second code snippet, I get 0 for console.log(getOffset("US/Eastern"));
    – Avraham
    Commented May 12, 2021 at 17:18
  • 3
    Changing timeZoneName: "short", to timeZoneName: "shortOffset", seems to fix this snippet so it works in Chrome 100, Firefox 99, and Node 18. I haven't tested other browsers or node versions. Otherwise, specifying a timezone of "US/Eastern" returns a timeZoneName of "EDT" which does not contain a parseable GMT offset.
    – Ray Waldin
    Commented Apr 20, 2022 at 1:34
  • 2
    There's a mistake in sign/minute rows. It should be if (minute) result += parseInt(minute); first and then if (sign === "+") result *= -1; Otherwise all the timezone offsets which have minutes are calculated incorrectly. For example, Asia/Calcutta offset is 5.5 meaning it should be -330 but your code gives -270.
    – Kasheftin
    Commented May 25, 2023 at 9:58
12

In general, this is not possible.

  • US/Eastern is an identifier for a time zone. (It's actually an alias to America/New_York, which is the real identifier.)

  • 240 is a time zone offset. It's more commonly written as -04:00 (Invert the sign, divide by 60).

  • The US Eastern Time Zone is comprised of both Eastern Standard Time, which has the offset of -05:00 and Eastern Daylight Time, which has the offset of -04:00.

So it is not at all accurate to say US/Eastern = 240. Please read the timezone tag wiki, especially the section titled "Time Zone != Offset".

Now you did ask for the current offset, which is possible. If you supply a date+time reference, then you can resolve this.

  • For the local time zone of the computer where the javascript code is executing, this is built in with .getTimezoneOffset() from any instance of a Date object.

  • But if you want it for a specific time zone, then you will need to use one of the libraries I listed here.

2
  • ECMA-262 defines timezone offset as UTC - localTime expressed in minutes. So I think it's reasonable in a javascript forum to write +240 where -04:00 might otherwise be used.
    – RobG
    Commented Dec 21, 2013 at 12:02
  • 8
    .getTimeZoneOffset() should be .getTimezoneOffset() without the uppercase Z Commented Aug 21, 2015 at 10:33
7

Following function can be used to return the UTC offset given a timezone:

const getTimezoneOffset = (timeZone, date = new Date()) => {
  const tz = date.toLocaleString("en", {timeZone, timeStyle: "long"}).split(" ").slice(-1)[0];
  const dateString = date.toString();
  const offset = Date.parse(`${dateString} UTC`) - Date.parse(`${dateString} ${tz}`);
  
  // return UTC offset in millis
  return offset;
}

It can be used like:

const offset = getTimezoneOffset("Europe/London");
console.log(offset);
// expected output => 3600000
8
  • 4
    This is slightly incorrect. The UTC offset should be positive for timezones that are behind it, and negative for timezones that are ahead of it. Therefore, the subtraction needs to be reversed: Date.parse(`${dateString} ${tz}`) - Date.parse(`${dateString} UTC`);. Otherwise, it won't align with the built-in Date.prototype.getTimezoneOffset. Commented Sep 30, 2020 at 17:38
  • 2
    Also, expected output for "Europe/London" should be 0
    – Avraham
    Commented Mar 4, 2021 at 16:19
  • 2
    @Avraham the offset depends on date due to DST. That's why the function takes a date as the second argument Commented Mar 5, 2021 at 5:17
  • 1
    timeStyle is invalid. It should be timeZoneName
    – dude
    Commented Jul 7, 2021 at 9:20
  • 1
    Results in NaN for me.
    – dude
    Commented Jul 7, 2021 at 9:37
1

You can do this using moment.js

moment.tz('timezone name').utcOffset()

Although this involves using moment-timezone.js

1
  • 1
    you must also have installed the moment-timezone package Commented Apr 11, 2018 at 5:14
-1

The answer of @ranjan_purbey results in NaN for me and the answer of @Weihang Jian throws an exception in Chrome (but works in Firefox).

Therefore, based on all the answers I came up with the following function which is basically a combination of both answers working together successfully for me:

function getTimeZoneOffset(timeZone) {
    const date = new Date().toLocaleString('en', {timeZone, timeZoneName: 'short'}).split(' ');
    const timeZoneName = date[date.length - 1];
    const offset = timeZoneName.slice(3);
    if (!offset) {
      return 0;
    }
    const matchData = offset.match(/([+-])(\d+)(?::(\d+))?/);
    if (!matchData) {
      throw new Error(`Cannot parse timezone name: ${timeZoneName}`);
    }
    const [, sign, hour, minute] = matchData;
    let result = parseInt(hour, 10) * 60;
    if (sign === '+') {
      result *= -1;
    }
    if (minute) {
      result += parseInt(minute, 10);
    }
    return result;
}
2
  • I do not get the timezone offset for New York, it just says EDT (vs UTC-4 or GMT-5) Commented Jul 30, 2021 at 13:34
  • This does not work. There is no offset value.
    – lowcrawler
    Commented Oct 25, 2022 at 21:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.