4

There are datetime strings that were concatenated from date and time values:

const localDatetime = `2017-01-01T12:00`;
const utcDatetime = `2017-01-01T12:00`;

and supposed to be converted to Date object.

In Firefox it is accepted as local time:

new Date('2017-06-12T12:00').toISOString() === '2017-06-12T08:00:00.000Z'

And in Chrome it is accepted as UTC time:

new Date('2017-06-12T12:00').toISOString() === '2017-06-12T12:00:00.000Z'

This looks inconsistent, to say at least.

What is the explanation for that? Which of these browsers is right and why?

What is cross-browser solution to perform this transformation properly for both local and UTC strings?

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 3
    Probably, because the language spec was never so detailed. This is the note you can find at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax): *Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.* – Álvaro González Jun 12 '17 at 14:19
  • 1
    It's a bug in Chrome, ISO 8601 date and time strings without a timezone should be treated as local. The bottom line is never use the built-in date parser, always manually parse strings with a bespoke function or library like [*fecha.js*](https://github.com/taylorhakes/fecha) or [*moment.js*](https://momentjs.com/). – RobG Jun 12 '17 at 22:23
  • @RobG That seems to be true, and as it appeared, it was finally fixed in Chrome 59. – Estus Flask Jun 12 '17 at 23:24
  • @estus—cool, but there are other browsers that do the same thing, e.g. Safari (and Chrome < 59) so the advice regarding not using the built-in parser stands (and will for a few years yet, sadly). I am very disappointed that the TC39 technical committee can spend so much time on mostly syntactic sugar and completely ignore giving Date decent formatting and parsing methods. – RobG Jun 13 '17 at 00:12
  • You can probably find in Google the story by the creators of JavaScript where they say they could barely copy the Java date API in two weeks because management wanted it done for a demo. – Álvaro González Jun 13 '17 at 14:51
  • @ÁlvaroGonzález It sounds plausible. It's zone detection was just broken. But I was able to solve this for UTC time with `new Date('2017-06-12T12:00+00:00')`. – Estus Flask Jun 13 '17 at 16:43

0 Answers0