0
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?

8
  • Possible duplicate of Compare two dates with JavaScript Commented Dec 29, 2016 at 22:59
  • 1
    Parsing strings is not recommended as per the note on MDN - it recommends parsing it manually (or using a library) Commented Dec 29, 2016 at 23:00
  • @J.Titus—this is about parsing dates, not comparing them. Commented Dec 30, 2016 at 1:37
  • 1
    As UnholySheep says, use a library or do it manually. If you only have one format to support, a parse function can be just 2 lines, see Simplest way to parse a Date in Javascript. Commented Dec 30, 2016 at 1:41
  • @RobG "...so that the two dates are considered equal." Sounds like comparison to me. Commented Dec 30, 2016 at 1:43

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Good info, but it doesn't actually answer the question: how to parse dates correctly in Javascript. ;-)
Dates are correctly parsed. The result is unexpected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.