How to Get List of All Timezones in JavaScript

How to get a list of all supported timezones?

I think that currently there is no easy way to get the list of supported timezones in node.js at runtime:

  • JavaScript Internationalization Api:

    The specification does not provide a way to get the list of supported timezones
  • NodeJs:

    NodeJs also does not provide a way go get the list of supported timezones

Workaround

A workaround is to somehow get a list of timezones and test each one separately.

There are many predefined timezone lists:

  • IANA Timezone database
  • Wikipedia: List of tz database time zones
  • Json Timezone List
  • Csv Timezone List

However, since we have a database application, we first get the list of all timezones supported by the database - see PostgreSql docs:

SELECT name
FROM pg_timezone_names
ORDER BY name;

and then check for each one if it is supported by nodejs (here's some typescript pseudo code):

  try {
new Intl.DateTimeFormat('en-US', {
timeZone
})
// timezone is valid - add to the valid list
} catch (e) {
// timezone is invalid - maybe write a log msg
}

Stackblitz Test

Now we have a list of all timezones that are valid in the database and in NodeJs.

There are currently (PostgreSql 12, NodeJs 14):

  • 547 valid timezones
  • 49 invalid timezones (i.e. known by PostgreSql, but not by NodeJs): e.g. America/Argentina/ComodRivadavia, US/Alaska, ..

How do I get timezones list using moment.js library?

For timezone, you should manually add timezone JS file made by yourself.

In this page, you can pick the zones up and generate a file to be loaded after you load moment.js first off.

You should have something like this, take a look:

<script src="/javascripts/modules/moment/moment-with-langs.min.js"></script>
<script src="/javascripts/modules/moment/moment-timezone.min.js"></script>
<script src="/javascripts/modules/moment/moment-timezone-data.js"></script>

The JS moment-timezone-data.js is the custom list of the timezones.

However, so far I know, MomentJS does not return for you a list of all timezones, because timezone can be changed as well. If you need to populate a select tag, I suggest you parse the timezone list manually from the link above.

Get all possible timezones from UTC offset

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/

Where does Intl API get it's time zone list?

According to MDN:

The only value implementations must recognize is
"UTC"; the default is the runtime's default time zone. Implementations
may also recognize the time zone names of the IANA time zone database,
such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York".

Changing list of time zone offset numbers to current times with JavaScript

I think this is what you are attempting to achieve (with significant changes).

Note the use of setInterval() rather than set time out and the structural changes to the HTML.

const utc = document.querySelector('.utc');
const collection = document.querySelectorAll('.timezone');
const outputs = document.querySelectorAll('.output');
const localeTZoffSet = new Date().getTimezoneOffset()/60 * 3600000;

setInterval(() => {
utc.textContent = calcTime(0);
collection.forEach((element, idx) => {
outputs[idx].textContent = calcTime(element.textContent);
});
});

function calcTime(offset) {
return "The local time is " + new Date(Date.now() + localeTZoffSet + (3600000 * offset)).toLocaleTimeString();
}
<div>UTC: <span class="utc"></span></div>
<div class="name">John Doe - <span class="output"></span></div>
<div class="timezone">-5</div>
<div class="name">Jane Doe - <span class="output"></span></div>
<div class="timezone">3</div>
<div class="name">Jim Smith - <span class="output"></span></div>
<div class="timezone">7</div>
<div class="name">Cathy Jones - <span class="output"></span></div>
<div class="timezone">-3</div>

How to get the list of all available timezone using moment-timezone

There is no straight way of getting in the format you want, directly from moment-timezone.

Try like below.

var moment = require('moment-timezone');
var timeZones = moment.tz.names();
var offsetTmz=[];

for(var i in timeZones)
{
offsetTmz.push(" (GMT"+moment.tz(timeZones[i]).format('Z')+") " + timeZones[i]);
}

Now, offsetTmz is an array of strings in the format you want.

This is how I am using it.

Hope this will help you.



Related Topics



Leave a reply



Submit