Reputation: 1169
When I'm working with date comparison in javascript, in the browser console I did perform the following operations.
new Date() >= new Date()
returned true
new Date() <= new Date()
returned true
this looked good as I thought both are equal, if I was correct then
new Date() == new Date()
should returns true
Interestingly it returned false. Then I performed below operations as well
new Date() > new Date()
returned false
new Date() < new Date()
returned false
new Date() != new Date()
returns true
which was also fine with my assumption.
If both the new Date() s were returning same time then == should return true along with the >= and <=, other wise either of > or < should return ture as != returning true.
Following table consists expected results and actual results for different cases.
Why is the ACTUAL results column not following any of its preceding columns?
Upvotes: 2
Views: 719
Reputation: 8033
Check for equality like you're doing compares the references to the objects. To compare the actual values of the objects themselves, the most common practice is to call getTime()
method, which will return the number of milliseconds since 1970-01-01 00:00:00 UTC.
Therefore, the following code will return true
:
(new Date()).getTime() == (new Date()).getTime()
Upvotes: 3
Reputation: 6366
Use Date.getTime
to compare the timestamp, otherwise you are simply comparing the objects, which we know aren't the same.
var d1 = new Date(),
d2 = new Date();
function fullCompare(a, b) {
console.log(a == b, a <= b, a >= b, a < b, a > b);
}
fullCompare(d1, d2);
fullCompare(d1.getTime(), d2.getTime());
Upvotes: 4