Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get TimeZone abbreviation? #14

Open
paulspiteri opened this issue Sep 25, 2024 · 2 comments
Open

Get TimeZone abbreviation? #14

paulspiteri opened this issue Sep 25, 2024 · 2 comments

Comments

@paulspiteri
Copy link

Is there a way to get the abbreviation of the current timezone? And specifically, how to determine if in daylight saving? (e.g. EDT or EST)
thanks

@enchorb
Copy link

enchorb commented Sep 30, 2024

+1

@csandman
Copy link

csandman commented Oct 25, 2024

This isn't the most elegant solution, but you can do it with the native .toLocaleString() function. You can't set up the arguments for it so that only the timezone name is returned, but you can extract it from the formatted string. Here's a TypeScript example:

export const getShortTimezoneName = (date: Date): string => {
  const timezoneDateStr = date.toLocaleString('en-US', {
    timeZoneName: 'short',
  });

  const timezoneName = timezoneDateStr.split(' ').pop();
  if (!timezoneName) {
    throw new Error('Could not parse timezone name');
  }

  return timezoneName;
};

This only works with TZDate (not TZDateMini) because it overrides the .toLocaleString function to add the specified timezone it's in as an argument: https://github.com/date-fns/tz/blob/main/src/date/index.js#L56-L61

Like I said, it's not the most elegant, but I've used it for a while with good success. Plus it will be timezone aware for EDT vs EST and PDT vs PST.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants