JavaScript check if timezone name valid or not
In environments that fully support IANA time zone identifiers in ECMA-402 (ECMAScript Internationalization API), you can try using a time zone in a DateTimeFormat
(or in the options of to toLocaleString
) and it will throw an exception if it is not a valid time zone. You can use this to test for validity, but only in environments where it is supported.
function isValidTimeZone(tz) {
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('Time zones are not available in this environment');
}
try {
Intl.DateTimeFormat(undefined, {timeZone: tz});
return true;
}
catch (ex) {
return false;
}
}
// Usage:
isValidTimeZone('America/Los_Angeles') // true
isValidTimeZone('Foo/Bar') // false
If you cannot be assured of your environment, then the best way would be with moment-timezone
!!moment.tz.zone('America/Los_Angeles') // true
!!moment.tz.zone('Foo/Bar') // false
Of course, you could always extract your own array of time zone names (perhaps with moment.tz.names()
and test against that.
I took Matt Johnson-Pin solution, after writing unit tests I found if to pass undefined
the function returns true
. So I made small update:
export const isValidTimeZone = (tz: unknown): boolean => {
try {
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
return false
}
if (typeof tz !== 'string') {
return false
}
// throws an error if timezone is not valid
Intl.DateTimeFormat(undefined, { timeZone: tz })
return true
} catch (error) {
return false
}
}
Thanks anyway I use this in production.
in typescript you could also do in a more cleaner way
public static isValidTimezone(timezone: string): boolean {
return moment.tz.zone(timezone) != null;
}
you need to also import
import moment = require("moment-timezone");