Can someone explain why the following snippets result in an invalid date object?
new Date(new Date().toLocaleString())
// or
Date.parse(new Date().toLocaleString())
This is expressly permitted by the ES5 specification's definition of Date.parse
(emphasis mine):
...all of the following expressions should produce the same numeric value in that implementation, if all the properties referenced have their initial values:
x.valueOf() Date.parse(x.toString()) Date.parse(x.toUTCString()) Date.parse(x.toISOString())
However, the expression
Date.parse(x.toLocaleString())
is not required to produce the same Number value as the preceding three expressions and, in general, the value produced by
Date.parse
is implementation-dependent when given any String value that does not conform to the Date Time String Format (15.9.1.15) and that could not be produced in that implementation by thetoString
ortoUTCString
method.
Since toLocaleString
is not required to produce a string conformant to the Date Time String Format YYYY-MM-DDTHH:mm:ss.sssZ
, it is allowable for its output not to be parsed correctly by Date.parse
.
new Date().toLocaleString()
returns the current date in a format new Date()
can't parse, resulting in unexpected dates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With