Skip to content

Instantly share code, notes, and snippets.

@jyeary
Created May 25, 2021 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyeary/d3b9bd91db1d61fc479832feb8084629 to your computer and use it in GitHub Desktop.
Save jyeary/d3b9bd91db1d61fc479832feb8084629 to your computer and use it in GitHub Desktop.
A Javascript method to determine the timezone of the browser.
function getTimezoneName() {
const today = new Date();
const short = today.toLocaleDateString(undefined);
const full = today.toLocaleDateString(undefined, { timeZoneName: 'short' }); // Trying to remove date from the string in a locale-agnostic way
const shortIndex = full.indexOf(short);
if (shortIndex >= 0) {
const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length); // by this time `trimmed` should be the timezone's name with some punctuation -
// trim it from both sides
return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, ''); }
else {
// in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name
return full;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment