Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 785
mest Avatar asked Sep 17 '25 23:09

mest


1 Answers

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.

like image 53
Michael Powers Avatar answered Sep 20 '25 15:09

Michael Powers