Case One:
new Date(Date.parse("Jul 8, 2005"));
Output:
Fri Jul 08 2005 00:00:00 GMT-0700 (PST)
Case Two:
new Date(Date.parse("2005-07-08"));
Output:
Thu Jul 07 2005 17:00:00 GMT-0700 (PST)
Why is the second parse incorrect?
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?
Case two actually gives me NaN
. Paste this into the browser address bar to test...
javascript:alert(new Date(Date.parse("2005-07-08")));
Probably because that is not a valid date string value. Invalid values may parse, but behavior is undefined.
The Date.parse
method is completely implementation dependent (new Date(string)
is equivalent to Date.parse(string)
).
I would recommend you to parse your date string manually, and use the Date constructor with the year, month and day arguments to avoid ambiguity:
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
While CMS is correct that passing strings into the parse method is generally unsafe, the new ECMA-262 5th Edition (aka ES5) specification in section 15.9.4.2 suggests that Date.parse()
actually should handle ISO-formatted dates. The old specification made no such claim. Of course, old browsers and some current browsers still do not provide this ES5 functionality.
Your second example isn't wrong. It is the specified date in UTC, as implied by Date.prototype.toISOString()
, but is represented in your local timezone.