Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten the timezone name list got from moment.js?

I am using moment.js ( the method I used is moment.tz.names()) to retrieve the timezone name list which enumerates over 500 cities across the world. The long list makes it not very efficient for the users to pick up the desired timezone. The question is whether there is a way to cut down on the size of the list, meaning group the cities in the same timezone offset together.

like image 342
ichbinblau Avatar asked Mar 10 '16 09:03

ichbinblau


2 Answers

This is something on the backlog for moment-timezone, in issue #227.

Below is the temporary workaround I provided there, which will shorten the list to 365 zone identifiers.

var names = Object.keys(moment.tz._zones)
    .map(function(k) { return moment.tz._zones[k].split('|')[0]; })
    .filter(function(z) { return z.indexOf('/') >= 0; })
    .sort();

This removes links and abbreviated zones from the list. We recognize this is still not ideal, and will improve upon this in a future release.

like image 63
Matt Johnson-Pint Avatar answered Oct 21 '22 05:10

Matt Johnson-Pint


In case someone else would like to filter out deprecated timezones:

const deprecatedTimeZones = ["UCT", "PST8PDT", "GB", "MST7MDT", "EST5EDT", "W-SU", "CST6CDT", "HST", "MST", "Universal", "EET", "WET", "EST", "CET", "MET", "GMT", "Etc"];
const deprecatedTimeZonesRegex = `^${deprecatedTimeZones.join("|^")}`;

const allowedTimeZones = moment.tz.names()
    .filter(timezone => timezone.startsWith("A") || !new RegExp(deprecatedTimeZonesRegex).test(timezone))
    .sort((timezoneA, timezoneB) => timezoneA.localeCompare(timezoneB))
    .map(timezone => ({
        timezone,
    }));

Using react-select (or something similar) in frontend for selection will make this fine.

like image 39
benjamin Avatar answered Oct 21 '22 07:10

benjamin