MDN Date page includes this at the top of the page:
var date1 = new Date('December 17, 1995 03:24:00');
var date2 = new Date('1995-12-17T03:24:00');
console.log(date1 === date2);
// expected output: false;
*Edit: it has been pointed out that depending on locale and JavaScript implementation, these two dates in the MDN example might actually not be identical. However the same results are obtained with the following:
var date1 = new Date('1995-12-17T03:24:00');
var date2 = new Date('1995-12-17T03:24:00');
console.log(date1 === date2);
// expected output: false;
The reason the equality operator doesn't return true is because Date
objects are...well...objects. JavaScript equality only returns true if it's literally the same object.
Two objects with identical properties are not considered equal by JavaScript (imagine how complex the algorithm would have to be to do a recursive analysis of every property within an object!)
var a = {test:1};
var b = a;
var c = {test:1};
console.log(a===b) // true
console.log(a===c) // false
This StackOverflow answer explains how to test date equality, by using getTime
:
var same = d1.getTime() === d2.getTime();
That way you're comparing numbers (epoch) instead of objects.