Quick JS Snippet: Prevent local timezone to be forced when not specified

·

2 min read

JavaScript's Date object can be very tricky sometimes.

One of the most mind-screwing issues a JS dev can stumble upon is local timezone enforcement

What do I mean by that?

Let's say our system (no matter if Node or Browser) has a UTC-0300 timezone, and we have this code:


const date = '2021-08-14'
const dateObj = new Date(date)
console.log(dateObj.getDate())

What do you think the output will be?

It will be 13

Why??

Because the local timezone is minus 3 hours, so when calling new Date(...) it will assume the specified date is referring to the UTC-0 timezone, i.e "zero offset"

As I said before, the JS runtime forces the local timezone upon dates when not specifying it. That's annoying and, when dealing with data from an API, if we aren't aware of this, it will work different for different clients! It will be messy.

I have come across this issue many times, and the first one involved a few hours of debugging and head-scratching with my coworkers.

So, whenever we know we will be dealing with that kind of string representation of a date (i.e, not a fully ISO-8601 formatted date string which includes timezone offset), we need to "neutralize" this odd JS behavior.

Today I stumbled upon this once again, but luckily I already had a Gist with some Date-related code to deal with this kind of things.

Specifically we'll use the function fixDate, which reads as:

/**
 * prevents local runtime timezone modifications when timezone not specified
 * @returns {Date}
 */
function fixDate(date) {
    const d = date;
    d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
    return d;
};

We just get the offset (in minutes) of the newly created Date object, and add it to the date.

Yes, it is hacky as you can get but it was the simplest quick-and-dirty fix to this common issue. Hope it helps someone else!