mest
mest

Reputation: 77

How to display the abbreviated name of the user's timezone (not GMT offset) in JavaScript?

I tried something like this:

function set_local_time(utcSeconds) {
    var d = new Date(0); // The 0 sets the date to the epoch
    d.setUTCSeconds(utcSeconds); //update date object with utcSeconds
    return d.toLocaleTimeString() + ', ' + d.toLocaleDateString() + ' ' + d.toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] //time, date timezone 
}

Which takes the time and converts it into the user's local time. It works perfectly within the USA (it displays PDT, EDT, etc.), but outside the USA, it just displays the GMT offset (e.g. GMT+1, GMT+8, etc.).

Is there a way to display the abbreviated name of the user's timezone internationally? So instead of GMT+1 for London, it would display BST instead?

Upvotes: 3

Views: 1635

Answers (2)

Anish Darji
Anish Darji

Reputation: 11

Without using any external libraries,

function getTimezoneShort(timeZone) {
    return new Intl.DateTimeFormat('en-US', {
        timeZone: timeZone,
        timeZoneName: 'short'
    }).formatToParts(new Date())
        .find(part => part.type == "timeZoneName")
        .value;
}

With Intl.DateTimeFormat you can have a date with abbreviated timezone and then use formatToParts property on current date to extract the abbreviated timezone.

usage

const localTimeZoneShort = getTimezoneShort('America/Toronto');

It works with daylight saving times as well.

Upvotes: 1

Michael Powers
Michael Powers

Reputation: 2050

You can't get this information directly from a Date object, but you can get it from the Intl.DateTimeFormat().resolvedOptions() interface like this:

let tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(tz);

This will give you the canonical name of the local time zone (e.g. America/New_York). If you want to map the time zone to an abbreviation including daylight savings time (e.g. EST, EDT, PST, EST) your best bet is to use a library like moment-timezone.

Upvotes: 3

Related Questions