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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With