Search code examples
javascripttimezonetimezone-offset

How to get UTC offsets from time zones of a particular region?


I have a small list of time zones as shown below. It also has the IANA names for time zones.

How do I use javascript to get the UTC offset for these time zones for the current time? I can use libraries like dayjs also, but I prefer plain js. I could not find any answers for this. Here is the closest question I could find How to get UTC Offset from a timezone. But, it has no answers.

1 - Pacific Standard Time, America/Los_Angeles
    Expected utc offset = -420
2 - Eastern Standard Time, America/New_York
    Expected utc offset = -240

Solution

  • The Intl specification includes a timeZoneName option for the DateTimeFormat constructor that controls how the time zone name is formatted. One of the options is 'longOffset', which is suitable for this purpose. Also, a clean way to isolate that string is to use the formatToParts function.

    function getCurrentOffset(timeZone) {
    
      // Create the formatter with the desired options.
      const format = new Intl.DateTimeFormat('en', {
        timeZone,
        timeZoneName: 'longOffset'});
    
      // Get the time zone name component, and slice off any leading abbreviation.
      const offsetString = format.formatToParts()
        .find(p => p.type === 'timeZoneName')
        .value
        .slice(3);
    
      // UTC and its equivalents must be handled directly, because Intl will return 'GMT'.
      if (offsetString === '') {
        return {offsetString: '+00:00', offsetMinutes: 0};
      }
    
      // Parse the hours and minutes from the result.
      const hours = offsetString.slice(0, 3);
      const minutes = offsetString.slice(4);
      const offsetMinutes = (-hours * 60) + ((hours < 0 ? 1 : -1) * minutes);
    
      // Return the ISO 8601 formatted offset string, as well as the total minutes offset.
      // Note, this returns minutes inverted, to match the behavior of the Date.getTimezoneOffset function.
      return {offsetString, offsetMinutes};
    }
    
    // some examples
    console.log('America/Los_Angeles', getCurrentOffset('America/Los_Angeles'));
    console.log('America/New_York', getCurrentOffset('America/New_York'));
    console.log('Asia/Kolkata', getCurrentOffset('Asia/Kolkata'));
    console.log('Pacific/Marquesas', getCurrentOffset('Pacific/Marquesas'));
    console.log('Etc/UTC', getCurrentOffset('Etc/UTC'));