I would like to create a function that converts timezone aliases names into the canonical name for said timezone.
Status of timezones from Wikipedia
For example if I had Africa/Accra
I would like to be able to look up that Africa/Abidjan
is the canonical name of the timezone.
function getCanonicalName(name) {
// TODO
}
getCanonicalName('Africa/Accra'); // => 'Africa/Abidjan'
I have tried using moment-timezone
and luxon
for parsing the zone name, but there doesn't seem to be a way to reverse engineer the canonical timezone as part of these libraries.
According to the moment-timezone
docs, you can get the Canonical Name of a timezone from the "packed" data representation, but looking at the implementation of pack
in their source code, it seems to just pass the source.name
through.
luxon
has a normalizeZone
helper but that seems to just return a Zone
instance from a wide range of input types. It does not, however, normalize the zone name. There is an isUniversal
flag on luxon Zone
s, but this flag seems to be related to DST, not the status of the timezone.
This may not recognize that specific zone as an alias since it was updated in September 2021:
But in general:
import moment from 'moment';
import momenttz from 'moment-timezone';
// From moment-timezone, but not exported
function normalizeName (name) {
return (name || '').toLowerCase().replace(/\//g, '_');
}
function getCanonicalName(name) {
const normalizedName = normalizeName(name);
// A canonical zone might exist
if (moment.tz._zones[normalizedName]) {
return moment.tz._names[normalizedName];
}
// If not, there'll be a link to a canonical name
const canonicalZoneNormalized = moment.tz._links[normalizeName(name)];
// And return the friendly name
return moment.tz._names[canonicalZoneNormalized];
}
console.log(getCanonicalName('Pacific/Wallis')); // => Pacific/Tarawa
console.log(getCanonicalName('Pacific/Tarawa')); // => Pacific/Tarawa
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With