from Hacker News

Ask HN: How do you solve timezone offset problem in Front end

by laangregor on 9/3/21, 2:04 PM with 3 comments

Hello everyone,

I'm having a challenging task. Angular application needs to show the date from the database object. It needs to stay the same, no matter where you are visiting the application. The only exceptions are the comments. I was testing this using Web Browser plugin.

I did a lot of research, but did not find a best practice. How would you solve this?

Currently I have created the following snippet:

  // To-Do: Needs to account summertime
  public dateToUTCDate(date: string | Date): Date {
    const time = date instanceof Date ? date.getTime() : Date.parse(date.substring(0, 10));
    return new Date(time + new Date(time).getTimezoneOffset() \* 60000);
  }
  • by Leftium on 9/3/21, 3:22 PM

    Generally, I think the best approach is to:

    1. Store UTC datetimes and do all calculations in UTC (or Unix epochs)

    2. Store the timezone separately

    3. When rendering dates/times in the UI, convert the UTC datetimes to local dates/times.

    I forgot where I first saw this recommended. I think it's recommended in a lot of places, though.

  • by pestatije on 9/3/21, 5:00 PM

  • by citiguy on 9/3/21, 2:16 PM

    Maybe I'm not understanding the question but best practice is usually to store everything in the database in UTC time (or epoch time) and do the conversion using a localtime offset when you display it.