new Date() and Date.parse() are bad at parsing dates

Published on in JavaScript

Last updated on

Use them only with certain date time formats, and use a library for parsing fancy formats.

Table of contents

They used to be discouraged

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.

Update: the MDN page was updated in June 2022. Now the page doesn't say anymore that the Date() constructor and Date.parse() are "strongly discouraged." From the linked pull request:

I think parsing ISO date strings is useful enough to not be completely discouraged.

Fancy formats are poorly supported

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

Certain formats are well-supported

Compare with a proper format that 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.

Moment.js vs others

If you have to parse fancy formats, consider using a library for that.

Probably don't choose Moment.js for new projects because Moment.js is in maintenance mode.

Consider Moment.js alternatives instead. I have been satisfied with date-fns.