4

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
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Those `Date`s may not necessarily be the same since they're created separately. What are the results if you create 1 at the top and then do the comparisons on it? – Carcigenicate Aug 02 '17 at 16:17

5 Answers5

4

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).

Max von Hippel
  • 2,856
  • 3
  • 29
  • 46
Pointy
  • 405,095
  • 59
  • 585
  • 614
3

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)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

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.

Evelyn Ma
  • 494
  • 2
  • 4
0

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
   
0

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.

pakkk
  • 289
  • 1
  • 2
  • 13