Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the canonical timezone name of a timezone alias?

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'

Things I've Looked into on my own

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 Zones, but this flag seems to be related to DST, not the status of the timezone.

like image 548
Souperman Avatar asked Oct 12 '25 07:10

Souperman


1 Answers

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
like image 89
Kevin Griffin Avatar answered Oct 14 '25 20:10

Kevin Griffin