Skip to content

Instantly share code, notes, and snippets.

@redoPop
Last active June 6, 2023 21:22
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save redoPop/3915761 to your computer and use it in GitHub Desktop.
Save redoPop/3915761 to your computer and use it in GitHub Desktop.
JavaScript: friendly timezone abbreviations in the client ("EDT", "CST", "GMT", etc.)
/*
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;
@amitsaurav
Copy link

On line #46 if:
tzAbbr[1].match(/[A-Z]/g)
returned null, you would have a javascript error.

@mygzi
Copy link

mygzi commented Jun 1, 2014

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

@andrejtest-675
Copy link

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/

@andrejtest-675
Copy link

andrejtest-675 commented Jul 4, 2021

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

@redoPop
Copy link
Author

redoPop commented Jul 5, 2021

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