JavaScript's Date() constructor is bad at parsing dates

Published on in JavaScript

Last updated on

And Date.parse() too. They are strongly discouraged due to browser differences and inconsistencies. Use proper date time formats only, or if not possible, use a library for parsing fancy formats.

From Date() constructor on MDN:

Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.

For example, the string "2021-01-10 12:47:29 UTC" is parsed correctly on Chrome, but results in "Invalid Date" on Firefox and iOS Safari (as of Jan 22, 2021):

new Date('2021-01-10 12:47:29 UTC')
//=> Chrome:     Sun Jan 10 2021 14:47:29 GMT+0200 (Eastern European Standard Time)
//   Firefox:    Invalid Date
//   iOS Safari: Invalid Date

Compare with a proper format which works in all three browsers:

new Date('2021-01-10T12:47:29.000Z') // Z = UTC
//=> Chrome:     Sun Jan 10 2021 14:47:29 GMT+0200 (Eastern European Standard Time)
//   Firefox:    Sun Jan 10 2021 14:47:29 GMT+0200 (Eastern European Standard Time)
//   iOS Safari: Sun Jan 10 2021 14:47:29 GMT+0200 (EET)

For proper formats, see Date Time String Format on MDN.

If you have to parse fancy formats, consider using a library for that. Don't choose Moment.js for new projects because Moment.js is in maintenance mode. Consider Moment.js alternatives instead.