Consider the image:
- A is showing 8 hours ago because the server time is in a different time zone (TZ) to the TZ of the browser
- B is what we want because that's the browser or local time which is computed with the TZ offset.
In the "olden" times, getting the browser or local datetime in reference to a server's datetime was to use a library like moment.js. But browsers have gone a long way.
Actually code:
const offsetLocalTime = new Date(dateStringFromServer);
offsetLocalTime.setHours(
offsetLocalTime.getHours() - offsetLocalTime.getTimezoneOffset() / 60,
);
The trick is the getTimezoneoffset() function. But it's not a silver bullet because:
- It only works with UTC or ISO dates. Remember, that UTC and ISO dates are "time keeping" standards NOT A FORMAT. Although, UTC and ISO are slightly different ways to track time, usually that's not a problem since the different between the two is a fraction of a second - which is only really significant if you're working in an ultra precise environment.
- It "guesses" the time zone of the OS so if the user configured his TZ incorrectly, then the computation is also off.