0

I have two dates both in a valid ISO-8601 format and I'm trying to convert them to a Date object.

console.log(new Date('2019-08-03T18:17:28.119Z'));
console.log(new Date('2019-05-09T08:25:22+0000'));
Output1: Sat Aug 03 2019 20:17:28 GMT+0200 (CEST)
Output2: Invalid Date

How come JavaScript doesn't recognize the second date as a valid ISO-8601 format?

How can I create a Date object out of that format?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Dino
  • 7,779
  • 12
  • 46
  • 85

1 Answers1

0

ECMA-262 requires that anything that doesn't conform to its version of ISO 8601 is implementation dependent. Formats that are close but not precise are likely to result in an invalid date in at least some browsers. Others may be more tolerant.

In this case, the offset "+0000" should be "+00:00". Similarly, replacing the "T" with a space may result in an invalid date, or not, depending on the implementation.

// Invalid date maybe
console.log(new Date('2019-05-09T08:25:22+0000').toString());

// valid
console.log(new Date('2019-05-09T08:25:22+00:00').toString());

To parse the problematic format, either add the missing colon before parsing, or (preferably) either write your own parse function (not difficult) or use a library (there are many good ones to chose from).

Also see Why does Date.parse give incorrect results?

RobG
  • 142,382
  • 31
  • 172
  • 209