Last active
May 17, 2024 04:05
-
-
Save redoPop/3915761 to your computer and use it in GitHub Desktop.
JavaScript: friendly timezone abbreviations in the client ("EDT", "CST", "GMT", etc.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/