javascriptnode.jsdatetimemomentjs

Get all possible timezones from UTC offset


I have the following value -
GMT -0800
How can I get the list of all time zones sharing this offset ?


Solution

  • Here's an example of listing timezones by offset, it's worth pointing out that the UTC offset for a given timezone changes due to daylight savings time for a lot of zones.

    <html>
    <head>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.js"></script>
    <script src="https://momentjs.com/downloads/moment.js"></script>
    <script src="https://momentjs.com/downloads/moment-timezone-with-data-2012-2022.js"></script>
    
    <script>
    
    
    function initialise() {
    
        $("#offsetSelector").on('change', function (event) {
           showTimeZones();
        });
    
        var startOffset = -12;
        var offsets = Array.from(Array(48).keys()).reduce((acc, val) => {
            acc.push(startOffset);
            startOffset += 0.5;
            return acc;
        }, []);
    
        offsets.forEach((offset) => {
            var selector = document.getElementById("offsetSelector");
            var el = document.createElement("option");
            el.textContent = offset;
            el.value = offset;
            selector.appendChild(el);
        });
    
        document.getElementById("offsetSelector").value = -8;
        showTimeZones();
    }
    
    function showTimeZones() {
    
        var utcOffset = $('#offsetSelector').val();
        var timeZones = moment.tz.names();
    
        var result = timeZones.filter((zone) => {
            var tz = moment.tz.zone(zone);
            /* We'll make the assumption we're looking for the offset outside of DST */
            var currentOffset = tz.utcOffset(new Date('2018-01-01'));
            return  (currentOffset === (-utcOffset*60));
        });
    
        $("#list").empty();
        console.log('Zones:');
        result.forEach((zoneName) => {
          console.log(zoneName);
          var ul = document.getElementById("list");
          var li = document.createElement("li");
          li.innerHTML = zoneName;
         // li.appendChild(document.createTextNode(zoneName));
          ul.appendChild(li);
        });
    }
    
    </script>
    
    </head>
    <body onLoad = "initialise()">
    <b>Offset (hours):</b>
    <select id="offsetSelector">
    </select> 
    
    <br/><br/><b>TimeZone list:</b><br/>
    <ul id="list"></ul>
    </body>
    </html>
    

    JSFiddle: https://jsfiddle.net/p9h5wgcr/