Skip to content

Instantly share code, notes, and snippets.

@phil-the-dev
Last active May 18, 2022 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phil-the-dev/eba6cdbf170822fbdee637087080ce71 to your computer and use it in GitHub Desktop.
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.
/**
* 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