97

When comparing date objects in Javascript I found that even comparing the same date does not return true.

 var startDate1 = new Date("02/10/2012");
 var startDate2 = new Date("01/10/2012");
 var startDate3 = new Date("01/10/2012");
 alert(startDate1>startDate2); // true
 alert(startDate2==startDate3); //false

How could I compare the equality of these dates? I am interested in utilizing the native Date object of JS and not any third party libraries since its not appropriate to use a third party JS just to compare the dates.

Rimian
  • 36,864
  • 16
  • 117
  • 117
Harshana
  • 7,297
  • 25
  • 99
  • 173

7 Answers7

148

That is because in the second case, the actual date objects are compared, and two objects are never equal to each other. Coerce them to number:

 alert( +startDate2 == +startDate3 ); // true

If you want a more explicity conversion to number, use either:

 alert( startDate2.getTime() == startDate3.getTime() ); // true

or

 alert( Number(startDate2) == Number(startDate3) ); // true

Oh, a reference to the spec: §11.9.3 The Abstract Equality Comparison Algorithm which basically says when comparing objects, obj1 == obj2 is true only if they refer to the same object, otherwise the result is false.

rioki
  • 5,988
  • 5
  • 32
  • 55
RobG
  • 142,382
  • 31
  • 172
  • 209
  • I'm upped answer, but is more right way to use _strict equals_ operator `===` in your examples? – Andrew D. Sep 30 '11 at 06:53
  • 5
    @AndrewD. using strict equals in this particular case doesn't make any difference on the results, this is because the equals operator in the examples, is always dealing with operands of the same type, @RobG is converting the values explicitly to Number (example 1 and 3) or in the example 2, we know that `Date.prototype.getTime` will always return a Number... – Christian C. Salvadó Sep 30 '11 at 07:25
  • @RobG: When you say " `obj1 == obj2` is true only if they refer to the same object", does that mean that the comparison (if both operands are objects) does not test for equality, but rather identity? Is my understanding of this correct? – Russell Dias Dec 06 '11 at 02:02
  • @RussellDias—yes. Where an object is assigned to a variable, the variable holds a reference to the object, so more than one variable can reference the same object. The rules for the abstract equality algorithm are quite long, but for objects it's pretty simple. – RobG Dec 06 '11 at 04:58
  • 13
    FYI, there is a significant performance difference between these approaches: http://jsperf.com/date-equality-comparison – Nick Zalutskiy Jan 13 '13 at 01:13
  • 2
    @Nick—even the slowest version takes less than a microsecond to run, so while there are comparative differences, in absolute terms the performance difference is negligible. The OP should just chose whichever approach suits best, likely using `getTime` is best for clarity (and happens to be fastest in the browsers I tested too). – RobG Jan 14 '13 at 05:30
  • 2
    @RobG You know, you are absolutely right. =) I was writing a library and did a test "just cuz." In real software it makes no difference whatsoever. – Nick Zalutskiy Jan 15 '13 at 05:12
  • @NickZalutskiy Thanks. I was going to right a similiar jspref but thought I'd hit up the comments first. ms' matter. – matchew Feb 20 '14 at 19:43
  • Could someone point me in the right direction to learn more about adding `+` in front of variables for comparison? – Hanna Jul 23 '14 at 20:45
  • 1
    @Johannes—see [*What is unary + used for in Javascript?*](http://stackoverflow.com/questions/9081880/what-is-unary-used-for-in-javascript) and [*The unary + operator*](http://xkr.us/articles/javascript/unary-add/). – RobG Jul 23 '14 at 23:09
30

Compare dates using getTime() returning number of milliseconds from epoch (i.e. a number):

var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var startDate3 = new Date("01/10/2012");
alert(startDate1.getTime() > startDate2.getTime()); // true
alert(startDate2.getTime() == startDate3.getTime()); //true

Also consider using Date constructor taking explicit year/month/date number rather then relying on string representation (see: Date.parse()). And remember that dates in JavaScript are always represented using client (browser) timezone.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
18

You do not need to use the getTime method- you can subtract a date object from another date object. It will return the milliseconds difference(negative, if the second is a later date)

var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");

var diff= (startDate1 -startDate2)

// evaluates to 0 if the dates have the same timestamp

kennebec
  • 102,654
  • 32
  • 106
  • 127
  • +1 simple and elegant, imo preferred solution: this uses built-in Date evaluation functionality without the need of coercion to a numeric timestamp – gdibble Jan 05 '16 at 22:25
  • 1
    Number coercion of dates is much slower (almost 10x for me) than reading `date.getTime()`, in case that matters to someone reading this. Here's a perf comparison: tinyurl.com/3c5svafe (it's a perf.link link, but SO won't let me use tinyurl links). – Jayant Bhawal Jun 16 '22 at 15:24
5

you can compare the actual milliseconds :

alert(startDate2.getTime() === startDate3.getTime());
gion_13
  • 41,171
  • 10
  • 96
  • 108
3

tl;dr

Use date.getTime() for comparisons.
Based on my testing, it was at least 25% than the next fastest alternative (date.valueOf()).

Details

Came across this in 2022. As others have already said, comparing like date1.getTime() === date2.getTime() is the way to go.

Someone else shared a jsperf link in an answer that seems broken for me right now, so decided to add some performance comparison of my own.

I created two arrays containing 1000 dates each. All dates will naturally be different instances (meaning direct === checks will fail), so what this benchmark does, is test what the fastest way is to convert a date to a primitive.

Here's the test data:

const data1 = Array.from({length: 1000}, () => new Date())
const data2 = Array.from({length: 1000}, () => new Date())

And here are the test cases (there's more in the link below):

// 1
data1.forEach((d1, i) => d1.getTime() === data2[i].getTime());

// 2
data1.forEach((d1, i) => d1.valueOf() === data2[i].valueOf());

// 3
data1.forEach((d1, i) => Number(d1) === Number(data2[i]));

// 4
data1.forEach((d1, i) => d1.toISOString() === data2[i].toISOString());

Result (use date.getTime())

Not a surprise that a date.getTime() conversion is much faster. It's around 25% faster than date.valueOf(), and between 10x and 100x faster than everything else (as far as I've checked).

Additionally, introducing optional chaining slowed the best case by almost 10% for me. Found that interesting. date.valueOf() also slowed down by 5% compared to its non optional chaining counterpart.

data1.forEach((d1, i) => d1?.getTime() === data2[i]?.getTime());

Benchmark link: here

Here's an image, in case the above link breaks at some point in the future.

benchmark image

Jayant Bhawal
  • 2,044
  • 2
  • 31
  • 32
0

You can also use the function valueOf()

 var startDate1 = new Date("02/10/2012").valueOf();
 var startDate2 = new Date("01/10/2012").valueOf();
 var startDate3 = new Date("01/10/2012").valueOf();
 alert(startDate1>startDate2); // 1326150000000 > 1328828400000   true
 alert(startDate2==startDate3); // 1328828400000 > 1326150000000  false
PeteBaser
  • 263
  • 1
  • 5
  • 15
0

One more way of comparing two dates would be converting dates to timestamps using "+" operator before the date.

So, let's say we have two dates:

const dateOne = new Date("10 January 1986")
const dateTwo = new Date("10 December 2020")
if(+dateOne == +dateTwo){
  //do something
}

and so on. This is really handy if you are sorting date objects too as you can use this in the sorting callback function.