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?

javanoob
  • 6,070
  • 16
  • 65
  • 88
  • Possible duplicate of [Compare two dates with JavaScript](http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – J. Titus Dec 29 '16 at 22:59
  • 1
    Parsing strings is not recommended as per [the note on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) - it recommends parsing it manually (or using a library) – UnholySheep Dec 29 '16 at 23:00
  • @J.Titus—this is about parsing dates, not comparing them. – RobG Dec 30 '16 at 01: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*](http://stackoverflow.com/questions/1258310/simplest-way-to-parse-a-date-in-javascript). – RobG Dec 30 '16 at 01:41
  • @RobG "...so that the two dates are considered equal." Sounds like comparison to me. – J. Titus Dec 30 '16 at 01:43
  • @RobG Thanks for your comment. I am using string split functions to parse the date string into correct date. – javanoob Dec 30 '16 at 01:44
  • @J.Titus But it is not duplicate. I am asking about comparison because the date objects created are different. I know it is tough to convince people that it is not duplicate once it is marked as duplicate. Anyway thanks for your time. – javanoob Dec 30 '16 at 01:46
  • Then leave out the part about equality and define what you mean by "correctly." Jochen answers your underlying question in his response. Read the JavaScript Date documentation. – J. Titus Dec 30 '16 at 01:50

1 Answers1

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

Jochen Bedersdorfer
  • 4,093
  • 24
  • 26