Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does parsing a locale date string result in an invalid date?

Can someone explain why the following snippets result in an invalid date object?

new Date(new Date().toLocaleString())
// or
Date.parse(new Date().toLocaleString())
like image 324
Chris Avatar asked Nov 01 '22 05:11

Chris


2 Answers

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 the toString or toUTCString 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.

like image 101
apsillers Avatar answered Nov 08 '22 02:11

apsillers


new Date().toLocaleString() returns the current date in a format new Date() can't parse, resulting in unexpected dates.

like image 44
Cerbrus Avatar answered Nov 08 '22 00:11

Cerbrus