Created
October 24, 2019 13:57
-
-
Save ianmstew/c58838fd5ef407b6ed477642b691eecb to your computer and use it in GitHub Desktop.
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 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