How to get the list of all available timezone using moment-timezone
Based on @Shrabanee answer and according to @Tenz comment - this is my solution with es6 Template literals and with sorting the list by the GMT + number instead of the timezone name:
timeZones = momentTimezone.tz.names();
let offsetTmz=[];
for(let i in timeZones)
{
offsetTmz.push(`(GMT${moment.tz(timeZones[i]).format('Z')}) ${timeZones[i]}`);
}
this.timeZoneNames = offsetTmz.sort();
Based on the answer by Erez Liberman and the answer by Matt Johnson about trimming the list I would like to add mine as a full Typescript
class, that sorts timezones with negative offset in reverse order
import * as moment from 'moment-timezone';
export class TimezoneData {
tzName: string;
tzPresentationName: string;
}
export class TimezoneUtils {
public static getTimezonesNames(): TimezoneData[] {
const arr: TimezoneData[] = [];
const names = moment.tz.names();
for (const name of names) {
if ((name.indexOf('/') < 0 && name !== 'UTC') || name.startsWith('Etc/')) {
continue;
}
const data = new TimezoneData();
data.tzName = name;
data.tzPresentationName = moment.tz(name).format('Z');
arr.push(data);
}
arr.sort((a, b) => {
if (a.tzPresentationName === b.tzPresentationName) {
if (a.tzName === 'UTC') {
return -1;
}
return a.tzName === b.tzName ? 0 : (a.tzName > b.tzName ? 1 : -1);
}
const afc = a.tzPresentationName.charAt(0);
const bfc = b.tzPresentationName.charAt(0);
if (afc === '-') {
if (bfc === '+') {
return -1;
}
return a.tzPresentationName > b.tzPresentationName ? -1 : 1;
}
if (bfc === '-') {
return 1;
}
return a.tzPresentationName > b.tzPresentationName ? 1 : -1;
});
arr.forEach(a => a.tzPresentationName = `${a.tzName} (GMT ${a.tzPresentationName})`);
return arr;
}
}
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.