Reputation: 6410
var date1 = new Date("Dec 29, 2016");
var date2 = new Date("2016-12-29");
console.log(date1);
//This prints "Thu Dec 29 2016 00:00:00 GMT-0500 (EST)"
console.log(date2);
//This prints "Wed Dec 28 2016 19:00:00 GMT-0500 (EST)"
console.log(date1 == date2);
//Prints false
How do I parse dates correctly in the above code so that the two dates are considered equal.
Looks like date2 object is not created correctly the way I want. How do I correct this?
Upvotes: 0
Views: 240
Reputation: 4122
Here's the explanation from the Date documentation:
Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
The parsing happens correctly, but in the second example, the time is treated as UTC, which then turns in Dec 28th in your local time zone.
More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Upvotes: 2