Last active
May 18, 2022 14:02
-
-
Save phil-the-dev/eba6cdbf170822fbdee637087080ce71 to your computer and use it in GitHub Desktop.
A helper function to properly set a date at midnight of the current browser's timezone.
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
/** | |
* Since Javascript's Date object will always return the time at midnight GMT | |
* but will then cast to the timezone on the client. | |
* Example: if you give 1/1/2022 12:00AM, EST people will see 12/31/2021 6:00PM EST. | |
* This function will account for the offset and return the correct time. | |
* Example: if you give 1/1/2022 12:00AM, EST people will see 1/1/2022 12:00AM EST. | |
* Taken from https://stackoverflow.com/a/39209842/864596 | |
* | |
* @param date: the date to be converted | |
* @returns the date in the current timezone with at the same Time | |
*/ | |
const newDateInCurrentTimezone = (date: Date | string) => { | |
const newDate = new Date(date); | |
const userTimezoneOffset = newDate.getTimezoneOffset() * 60000; | |
return new Date(newDate.getTime() + userTimezoneOffset); | |
}; | |
export default newDateInCurrentTimezone; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment