Created
October 19, 2022 07:41
-
-
Save gtchakama/bf39e766189ce5858882b612dcb8a004 to your computer and use it in GitHub Desktop.
Initialize a Date with Time Zone using JavaScript
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
const date = new Date(); | |
// β Get a string according to a provided Time zone | |
console.log( | |
date.toLocaleString('en-US', { | |
timeZone: 'America/Los_Angeles', | |
}), | |
); // ποΈ "1/15/2022, 11:54:44 PM" | |
console.log( | |
date.toLocaleString('de-DE', { | |
timeZone: 'Europe/Berlin', | |
}), | |
); // ποΈ "16.1.2022, 08:54:44" | |
// β Or get a Date object with the specified Time zone | |
function changeTimeZone(date, timeZone) { | |
if (typeof date === 'string') { | |
return new Date( | |
new Date(date).toLocaleString('en-US', { | |
timeZone, | |
}), | |
); | |
} | |
return new Date( | |
date.toLocaleString('en-US', { | |
timeZone, | |
}), | |
); | |
} | |
const laDate = changeTimeZone(new Date(), 'America/Los_Angeles'); | |
console.log(laDate); // ποΈ "Sun Jan 15 2022 11:54:44" | |
const berlinDate = changeTimeZone(new Date(), 'Europe/Berlin'); | |
console.log(berlinDate); // ποΈ "Sun Jan 16 2022 08:54:44" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment