-
-
Save redoPop/3915761 to your computer and use it in GitHub Desktop.
/* | |
Given a date, tzAbbr returns a short, friendly name for the | |
user's time zone on that date, or an empty string if their | |
client's Intl support is missing or incomplete. | |
For example, a user in New York might see: | |
tzAbbr(new Date()) // => "EST" | |
Time zones are locale-dependent. Users traveling outside of | |
their locale will see a GMT offset since they may not be | |
familiar with local time zone abbreviations. | |
For example, an American in Australia might see: | |
tzAbbr(new Date()) // => "GMT+10" | |
*/ | |
const formatter = typeof Intl !== 'undefined' | |
&& Intl?.DateTimeFormat('default', { | |
timeZoneName: 'short' | |
}); | |
const tzAbbr = date => | |
formatter?.formatToParts?.(date) | |
.find(part => part.type === 'timeZoneName') | |
?.value || ''; | |
export default tzAbbr; |
I've found IE8 to return UTC, not GMT. Just got the date string below via BrowserStack's simulator. Might be worth checking for both.
Fri May 30 04:00:00 UTC+0100 2014
It gives wrong results.
For Moscow standart time, it gives "MST", and there's no such timezone, it's "MSK".
I know it's 9 years old and there are more recent and better solutions but just wanted to WARN others because this page can be easily accessed from Google.
Maybe a solution is to introduce some dictionary like https://www.timeanddate.com/time/zones/
Also I know it's better to find some library for this task but if someone is okay with using a pure javascript solution, here's an example snippet. Please note timezone names are hard-coded but I don't expect the names change (the names, offset could change).
https://gist.github.com/andrejtest-675/61bee6d4c13a72e5c9b0f6597371ee91
Thanks for the nudge – I'd forgotten all about this gist! The RegEx approach was the best I could come up with 9 years ago, but it doesn't work as well with newer browsers.
We now have the Intl
library, which provides a more robust solution. I've updated the gist, but recommend folks read up on Intl.DateTimeFormat itself.
On line #46 if:
tzAbbr[1].match(/[A-Z]/g)
returned null, you would have a javascript error.