8

Converting server time to any given local timezone is a pain in the ass.. at least in JS.

Here's what I've got:
convertNowToTimezone = (localOffset) => {
let d = new Date();
let millis = d.getTime() + (d.getTimezoneOffset() * 60000); //convert server local time to UTC millisec
d.setTime(millis - (localOffset * 60000)); //convert UTC millisec to required local time
return d;
}

where I pass localOffset as -330 (IST offset).
Works in chrome console but gives a diff of 4min in the server side nodejs I'm running it in..

🤬🤬😡😡😡😡😡

Comments
  • 0
    moment.js makes local life a lot easier
  • 0
    @Buggz yet moment is a piece of shit. Still is the only library that handle decently local time.

    If u feel like it u can always use utc methods in the date class
  • 0
    Date and time is one of the things I refuse to even try to handle myself, it's the invention with the most exceptions and edge cases in human history.
  • 0
    @Buggz I don't like the idea of adding another dependency for one utility function.
  • 0
    Moment.js to the rescue. At least this is one area that PHP simplified quite a lot
  • 0
    @AnonymusPanther you have to. But maybe for your use case take a look at date-fns u can cherry pick function by function so you don't add any weight to your code
  • 0
    Why not store the date in UTC on the server and let the browser handle the local timezone on the client?

    If you work with ISO date strings (preferably), parsing the date on the Frontend is really straightforward:
    let d = new Date(isoString);

    If you still work with timestamps, things like Date.now() and (new Date()).getTime() all return UTC timestamps.
  • 1
    Generally JS is a pain anyway
  • 0
    There's moment.js and day.js and so many modules for that sort of stuff and you can even just use ISO date strings.
Add Comment