Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created October 19, 2022 07:41
Show Gist options
  • Save gtchakama/bf39e766189ce5858882b612dcb8a004 to your computer and use it in GitHub Desktop.
Save gtchakama/bf39e766189ce5858882b612dcb8a004 to your computer and use it in GitHub Desktop.
Initialize a Date with Time Zone using JavaScript
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