Search code examples
javascripttimezonemomentjstimezone-offset

Get timezone name/list using timezone offset


I am having the time zone offset using the below code. I want to find out the list of timezone names associated with the timezone offset.

new Date().getTimezoneOffset().toString()


Solution

  • I think the you have to use moment-timezone.js library for this.

    (Link here: https://momentjs.com/timezone/)

    The approach should go along this lines:

    1. import the library (Note: this library is dependent on moment.js library - import that before)
    2. use moment.tz.names() function to get all the available timezone locations.
    3. use moment.tz.zone(name) function to get the zone object
    4. use the offsets property from the zone object to get the location offset
    5. create a map to hold the same offset names.
    6. loop through the offsets (one location can share multiple offsets) and add them to the map as well as the name of location to each key.
    7. access that map with specific offset and get the list of timezones.

    The code will look something like this:

    const tzNames = moment.tz.names();
    const map = new Map();
    
    for (const name of tzNames) {
      const offsets = moment.tz.zone(name).offsets;
      
      for (const offset of offsets) {
          if (!map.has(offset)) {
              map.set(offset, new Set());
          }
    
          map.get(offset).add(name);
      }
    }
    
    const currentOffset = new Date().getTimezoneOffset();
    const offsetList = map.get(currentOffset);
    
    console.log('currentOffset: ' + currentOffset);
    console.log('offset list size: ' + offsetList.size);
    console.log('Total different offsets: ' + map.size);
    
    console.log('List items: ');
    for (const item of offsetList) {
      console.log(item);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>