Can anyone explain this unexpected behavior?
console.log(new Date() == new Date()); // false
console.log(new Date() >= new Date()); // true
console.log(new Date() <= new Date()); // true
Can anyone explain this unexpected behavior?
console.log(new Date() == new Date()); // false
console.log(new Date() >= new Date()); // true
console.log(new Date() <= new Date()); // true
The ==
comparator compares the object references, and two different objects will never be equal.
The relational comparators, however, will compare the numeric values of the dates (the underlying timestamps). Thus if you tried
new Date().getTime() == new Date().getTime()
you'd get true
. In this case, the =
part of the >=
and <=
operators makes the statements true (as in the example above).
The first is comparing equality of 2 different objects.
The >=
and <=
will first coerce the Date objects to Number
Simplified resultant example:
{} == {} // false
41765490 <= 41765490 // true
41765490 >= 41765490 // true
For the first case of ==
you can also force the coersion to number doing:
+new Date() == +new Date() // true (assuming no lag between creating both)
Date() is object.
new Date()
will generate an object(let's call it a)
and == new Date()
will generate another object(call it b)
so object a == object b will return false.
But >=
or <=
will compare the value of the objects, it will return true as long as the value is the same.
This is how you compare dates i Javascript.
(date1.getTime() === date2.getTime())
var date1 = new Date();
var date2 = new Date();
console.log(date1.getTime() === date2.getTime()); // true
console.log(date1 >= date2); // true
console.log(date1 <= date2); // true
I googled and I found the response in Stack Overflow:
https://stackoverflow.com/a/41980287/2520689
As it said:
Using instead a constructor as new Date(), each instance is unique (the two instances of the same constructor are still different to each-other), this is the reason why they are not equal when compared.