DEV Community

Cover image for Fix Javascript Date Woes
Philippe Batigne
Philippe Batigne

Posted on

Fix Javascript Date Woes

If you've ever worked with dates returned from an API in javascript/typescript, you've probably dealt with the "ugh, why did it convert to UTC then add the timezone". I found this helpful function that will take any Date and apply the Timezone difference while retaining the original time.

For example, without this function if you give the Date class 1/1/2022 12:00AM, people in the EST Timezone will see 12/31/2021 6:00PM EST.

With this function, if you give the Date class if you give 1/1/2022 12:00AM, people in the EST Timezone will see 1/1/2022 12:00AM EST.

Code originally found from StackOverflow

const newDateInCurrentTimezone = (date: Date | string) => {
  const newDate = new Date(date);
  const userTimezoneOffset = newDate.getTimezoneOffset() * 60000;
  return new Date(newDate.getTime() + userTimezoneOffset);
};

export default newDateInCurrentTimezone;
Enter fullscreen mode Exit fullscreen mode

Gist: https://gist.github.com/phil-the-dev/eba6cdbf170822fbdee637087080ce71

Top comments (0)