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;
@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