Created
May 25, 2021 12:55
-
-
Save jyeary/d3b9bd91db1d61fc479832feb8084629 to your computer and use it in GitHub Desktop.
A Javascript method to determine the timezone of the browser.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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