Skip to content

Instantly share code, notes, and snippets.

@redoPop
Last active May 17, 2024 04:05
Show Gist options
  • 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;
@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