new Date(Date.parse("Jul 8, 2005"));
Fri Jul 08 2005 00:00:00 GMT-0700 (PST)
new Date(Date.parse("2005-07-08"));
Thu Jul 07 2005 17:00:00 GMT-0700 (PST)
Why is the second parse incorrect?
The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). As until ES5, parsing of strings was entirely implementation-dependent.
According to MDN, it is not recommended to use Date. parse. Their reasoning provided is: ”… until ES5, parsing of strings was entirely implementation dependent.
Its parse function can figure out what format a string is in without having to specify the format like you do with datetime. strptime . dateutil. parse is a better alternative if the exact format of a legal ISO string is unknown.
Then the the parse function outputs a date object, which is easier to store and manipulate than a date string. Parsing a whole language. This is what parsing always means. Whole programming languages are parsed according to how the parts are built together in the language definition.
Until the 5th edition spec came out, the Date.parse
method was completely implementation dependent (new Date(string)
is equivalent to Date.parse(string)
except the latter returns a number rather than a Date
). In the 5th edition spec the requirement was added to support a simplified (and slightly incorrect) ISO-8601 (also see What are valid Date Time Strings in JavaScript?). But other than that, there was no requirement for what Date.parse
/ new Date(string)
should accept other than that they had to accept whatever Date#toString
output (without saying what that was).
As of ECMAScript 2017 (edition 8), implementations were required to parse their output for Date#toString
and Date#toUTCString
, but the format of those strings was not specified.
As of ECMAScript 2019 (edition 9) the format for Date#toString
and Date#toUTCString
, have been specified as (respectively):
providing 2 more formats that Date.parse
should parse reliably in new implementations (noting that support is not ubiquitous and non–compliant implementations will remain in use for some time).
I would recommend that date strings are parsed manually and the Date constructor used with year, month and day arguments to avoid ambiguity:
// parse a date in yyyy-mm-dd format function parseDate(input) { let parts = input.split('-'); // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]]) return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based }
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