Stop javascript Date function from changing timezone offset

While MomentJS is a great library, it may not provide a solution for every use case. For example, my server provides dates in UTC, and when the time portion of the date is not saved in the db (because it’s irrelevant), the client receives a string that has a default time of all zeros – midnight – and ends with an offset of +0000. The browser then automatically adjusts for my local time zone and pulls the time back by a few hours, resulting in the previous day.

This is true with MomentJs as well.

One solution is to slice off the time portion of the string, and then use MomentJS as described in the other answers.

But what happens if MomentJS is not a viable option, i.e. I already have many places that use a JS Date and don’t want to update so many lines of code? The question is how to stop the browser from converting dates based on local time zone in the first place. And the answer is, when the date is in ISO format, you cannot.

However, there is no rule that says the string you pass to JavaScript’s Date constructor must be in ISO format. If you simply replace the - that separates the year, month, and day with a /, your browser will not perform any conversion.

In my case, I simply changed the format of the Dates server-side, and the problem was solved without having to update all the client-side JS dates with MomentJS.

Note that the MDN docs for JavaScript’s Date class warn about unpredictable browser-behavior when parsing a string to create a Date instance.

Leave a Comment