Skip to content

Instantly share code, notes, and snippets.

@ianmstew
Created October 24, 2019 13:57
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 ianmstew/c58838fd5ef407b6ed477642b691eecb to your computer and use it in GitHub Desktop.
Save ianmstew/c58838fd5ef407b6ed477642b691eecb to your computer and use it in GitHub Desktop.
(() => {
function getLocale() {
// IE 11 does not support navigator.languages
return navigator.languages ? navigator.languages[0] : navigator.language;
}
function isTimezoneSupported(timezone) {
try {
new Date().toLocaleDateString(getLocale(), { timeZone: timezone });
} catch (err) {
if (err instanceof RangeError) {
return false;
}
throw err;
}
return true;
}
function formatDateWithTimezone(date, timezone) {
if (!isTimezoneSupported(timezone)) {
return '';
}
const formattedDate = date.toLocaleDateString(getLocale(), { timeZone: timezone });
const formattedTime = date.toLocaleTimeString(getLocale(), { timeZone: timezone });
return formattedDate + ' ' + formattedTime + ' ' + timezone;
}
console.log({
utc: formatDateWithTimezone(new Date(), 'UTC'),
'America/New_York': formatDateWithTimezone(new Date(), 'America/New_York'),
'Asia/Kolkata': formatDateWithTimezone(new Date(), 'Asia/Kolkata'),
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment