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:
"March 6th 2015"
)"2015-06-03"
, without the time or timezone)What I would like to know is, given these two assumptions:
"2021-11-26T23:04:00.778Z"
)Can I reliably use new Date(string)
?
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.