JavaScript check if timezone name valid or not

Viewed 11058

Is there a way to check if timezone name valid or not in JavaScript without using external library?

When user enters timezone name in text field I want to verify whether zone is valid or not?

I know we can do it easily using moment-timezone library. But I don't want to use any extra library. I'm looking for pure JavaScript way.

isValidTimeZone(name) {
//return true/false  
}

isValidTimeZone('Asia/Colombo'); //returns true
isValidTimeZone('America/Los_Angeles'); //returns true
isValidTimeZone('MyTimeZone/ME'); //returns false
3 Answers

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");

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.

Related