Last active
September 12, 2022 19:28
-
-
Save tshddx/017f88f7094cc017b7e5f7b7ead396d8 to your computer and use it in GitHub Desktop.
JavaScript utility to shift a date to UTC
This file contains 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
/* | |
Note: if you only want to format a date as a string and not do any date | |
manipulation, you can use provided formatting functions to specify a time zone: | |
const date = new Date(dateString); | |
const formattedDate = date.toLocaleDateString('en-US', { timeZone: 'UTC' }); | |
All JavaScript Date objects are in the browser's local time zone. There's no way | |
around that. This means that if you receive a date string from the backend and | |
create a Date object with `new Date(unixTimestampOrISOString)` that Date object | |
will potentially be on a different calendar date than it is in UTC. | |
Here's a demonstration of this problem with a computer in Pacific Daylight Time. | |
Passing individual year, month, and day arguments to the Date constructor works | |
fine, but passing a date string results in a Date object on a different calendar | |
date: | |
new Date(2022, 8, 30) | |
Fri Sep 30 2022 00:00:00 GMT-0700 (Pacific Daylight Time) | |
new Date('2022-08-30') | |
Mon Aug 29 2022 17:00:00 GMT-0700 (Pacific Daylight Time) | |
This function will essentially shift the Date object to the correct UTC year, | |
month, and day. But note, the Date object that's returned will still *think* | |
that it's in the local time zone, so e.g. if you apply this function multiple | |
times it will keep shifting. | |
*/ | |
function shiftDateToUTC(date) { | |
const utcDate = new Date( | |
date.getUTCFullYear(), | |
date.getUTCMonth(), | |
date.getUTCDate(), | |
date.getUTCHours(), | |
date.getUTCMinutes(), | |
date.getUTCSeconds() | |
); | |
return utcDate; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment