27

When I create two identical JavaScript Date objects and then compare them, it appears that they are not equal. How to I test if two JavaScript dates have the same value?

var date1 = new Date('Mon Mar 11 2013 00:00:00');
var date2 = new Date('Mon Mar 11 2013 00:00:00');
console.log(date1 == date2); //false?

JS Fiddle available here

ry8806
  • 2,258
  • 1
  • 23
  • 32
Bryce
  • 6,440
  • 8
  • 40
  • 64
  • also check [this](http://stackoverflow.com/questions/7244513/javascript-date-comparisons-dont-equal) – Arun P Johny Mar 18 '13 at 05:47
  • 1
    To see if two dates are equal, you could do `+a == +b` or `!(a - b)`, but that may be a bit obfuscated. Don't leave parsing random date strings to the Date constructor, either provide a standards compliant string (which isn't consistently supported yet) or provide values per [ECMA-262](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.1). – RobG Mar 18 '13 at 05:53

3 Answers3

53

It appears this has been addressed already.

To check whether dates are equal, they must be converted to their primitives:

date1.getTime()=== date2.getTime()
//true
Community
  • 1
  • 1
Bryce
  • 6,440
  • 8
  • 40
  • 64
23

First of all, you are making a sound mistake here in comparing the references. Have a look at this:

var x = {a:1};
var y = {a:1};

// Looks like the same example huh?
alert (x == y); // It says false

Here, although the objects look identical they hold different slots in memory. Reference stores only the address of the object. Hence both references (addresses) are different.

So now, we have to compare the values since you know reference comparison won't work here. You can just do

if (date1 - date2 == 0) {
    // Yep! Dates are equal
} else {
   // Handle different dates
}
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • 2
    Good answer - especially because I find date.GetTime() misleading (suggests it will get the time to me (even though I know there isn't a time object)) – Neil Thompson Dec 03 '14 at 17:59
0

I compare many kinds of values in a for loop, so I wasn't able to evaluate them by substracting, instead I coverted values to string before comparing

var a = [string1, date1, number1]
var b = [string2, date2, number2]
for (var i in a){
  if(a.toString() == b.toString()){
    // some code here
  }
}