Home > other >  Is `new Date(string)` reliable in modern browsers, assuming the input is a full ISO 8601 string?
Is `new Date(string)` reliable in modern browsers, assuming the input is a full ISO 8601 string?

Time:11-27

There are many warnings out there about not using new Date(string) (or the equivalent Date.parse(string) in javascript because of browser inconsistencies. MDN has this to say:

It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).

However when you read on, most of the warnings about implementation-specific behaviour seem to be for these scenarios:

  • Old browsers (like, pre-ES5 old)
  • Non-ISO 8601 inputs (e.g. "March 6th 2015")
  • Incomplete ISO 8601 inputs (e.g. "2015-06-03", without the time or timezone)

What I would like to know is, given these two assumptions:

  • Modern browsers (say, anything from 2020 onwards)
  • Full ISO 8601 inputs (e.g. "2021-11-26T23:04:00.778Z")

Can I reliably use new Date(string)?

CodePudding user response:

Yes. The format of acceptable Date strings in JavaScript is standardized:

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 calendar date extended format. The format is as follows:

    YYYY-MM-DDTHH:mm:ss.sssZ

From ECMAScript current draft under the section heading " Date Time String Format".

This is the only standard for parsing date strings presented in the spec and hence the aim of date libraries will be to format dates into this format before calling new Date or Date.parse. I can't comment on what the "simplification" of the ISO standard is, but the format asked about in the post matches that of the [ECMAScript] standard.

Note the standard continues on to state date only forms

YYYY
YYYY-MM
YYYY-MM-DD

are accepted and that time formats, optionally followed by a UTC offset, of

THH:mm
THH:mm:ss
THH:mm:ss.sss

may be used following the date component.

CodePudding user response:

Yes, it is reliable to use ISO 8601 inputs to new Date.

As the documentation you quoted indicated, this was standardised with ES5, and according to MDN's compatibility table, Internet Exploder 8 (RIP) was the last browser not to support it.

  • Related