Search code examples
javascriptresttimezonehandlebars.jsformatjs

Time zone issue when using REST Api and JS


I'm using FormatJS library along with Handlebars to display a list of events that occured in the past. I'm calling for an endpoint on my server's REST API which returns me the list of events in Json, with datetimes to display for each event. ATM I'm saving datetimes in the DB using GMT time zone.

So when I'm getting my Json, I'm handling datetimes like this :

{{formatRelative commentDate}}

My issue is, since the datetimes are stocked in GMT, they display also like that. For example, since I'm on a GMT+2 timezone, as soon as a new event is created and shows up on the list, I see it "happened 2 hours ago" while it should be "a few seconds ago".

So, is there a way I can handle this ? Am I making a mistake in saving datetimes in GMT in my DB, and if so, how would you handle datetimes coming from different timezones and displaying them to people in other timezones ?

Of course I could customize the formatRelative helper to play with getTimezoneOffset and get the wanted result, but I wanted to know if there is something better to do.

Thanks a lot ahead !


Solution

  • The key to understanding your question is what you wrote in the comments:

    Getting the Json, containing datetimes in the format 2016-02-28 10:15:53 - that's UTC time

    You should ensure the value in JSON is in full ISO8601 format, including the appropriate offset or Z character to indicate UTC: 2016-02-28T10:15:53Z

    Without the offset, most implementations will consider the value to be represented in local time, which explains your results.

    Thus, the problem is with your server-side code, not your JavaScript code. There may be a client-side workaround you could apply when the date string is parsed from JSON, but really the best solution would be to qualify it at the server.