Alexey
Alexey

Reputation: 2582

Convert Date to local time zone with toLocaleString() method (Firefox)

The time zone on my computer is UTC+3. I have the following JavaScript code:

// date in UTC time zone
var date = new Date('2015-10-09T20:00:00.000Z');

var options = {year: "numeric", month: "2-digit", day: "2-digit"};
var output = date.toLocaleString('en-us', options);

In IE and Chrome this code outputs 10/09/2015 (i.e. 9 Oct 2015) which is correct as 20:00 UTC is 23:00 my time (and it is still 9 Oct).

However, in Firefox the output is 10/10/2015 (i.e. 10 Oct 2015) - this is the problem.

If I change the initial date/time string to 2015-10-09T19:59:00.000Z (one minute back compared to the initial value), Firefox gives the correct date (9 Oct 2015).

Why the toLocaleString() method in Firefox behaves this way?

All browsers are installed on the same computer. Date.getTimezoneOffset() returns -180 in all browsers.

Upvotes: 3

Views: 3945

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241485

You've stumbled upon a bug in Firefox. I can reproduce your results, and explain them.

There are multiple time zones that use the UTC+3 offset, but from your results I can infer that you are set to Moscow time.

In 2014, Russia set all of its time zones back one hour. This moved the base offset for Moscow from UTC+4 to UTC+3. The bug is that Firefox appears to be confused and is using the old +4 offset in its toLocaleString function, even though it correctly identifies the +3 offset in the other functions such as getTimezoneOffset and toString.

You can see this when trying a different time zone that has not gone though this sort of change. On Windows, I pick "(UTC+03:00) Nairobi" (which has the underlying time zone ID of "E. Africa Standard Time"). It is defined as a fixed zone that has always been on UTC+3.

test 1

Then I close Firefox and change my time zone to "(UTC+03:00) Moscow, St. Petersburg, Volgograd (RTZ 2)" (which has the ID "Russian Standard Time"). Then I restart Firefox and do the same test:

test 2

As you can see, in the first test it gets the correct answer for both toString and toLocaleString, but in the second test they are different. The toLocaleString has applied the wrong offset, getting to midnight on October 10 instead of the correct 23:00 on October 9.

Of course when you strip away the time with the formatting options this is harder to see, but it is the same underlying bug.

This bug has already been reported to Mozilla here. If it is important to you, you should consider voting on it.

As far as what to do - In general, I don't currently recommend the toLocaleString function. It's great that ECMA-402 has defined this, but it's not yet widely implemented, and the implementations are somewhat inconsistent as far as which options they support. In a few years this may be the right way to go, but for now I recommend using moment.js instead.

Upvotes: 2

Related Questions