Art
Art

Reputation: 24567

JavaScript date comparison

Why does the equality operator return false in the first case?

var a = new Date(2010, 10, 10);
var b = new Date(2010, 10, 10);
alert(a == b); // <- returns false
alert(a.getTime() == b.getTime()); // returns true

Why?

Upvotes: 11

Views: 10167

Answers (4)

user505150
user505150

Reputation: 15

I'm sorry guys, but this is idiotic... especially the bit about having two clocks.

==, by definition compares VALUES, whereas === compares references. Saying that == fails for non-primitives breaks the language's own syntactical structure. Of course, === would fail in the initial example, as the two dates are clearly two distinct pointers to two distinct memory-spaces, but, by the very definition of the JS spec, == should return TRUE for the comparison of two dates whose value is the same point in time.

Yet another reason I hate JS...

Sorry to rant, but this just kicked my butt for an hour.

As an aside, you can use valueOf() to force the comparison of the values, and that will return true... it is redundant with == but it works.

Upvotes: -1

Sean Kinsey
Sean Kinsey

Reputation: 38046

Since dates are built-in objects, and not primitives, an equality check is done using the objects references.

In this case, objects a and b are not the same object, and so the test fails.
You can see the same using

var a = new String("a");
var b = new String("a");
alert(a == b); //false

By using .getTime or .valueOf you are converting the objects value into a primitive, and these are always compared by value rather than by reference.

If you want to do a comparison by value of two dates there is also a more obscure way to do this

var a = new Date(2010, 10, 10);
var b = new Date(2010, 10, 10);

alert(+a == +b); //true

In this case the unary + operator forces the javascript engine to call the objects valueOf method - and so it is two primitives that are being compared.

Upvotes: 28

kennebec
kennebec

Reputation: 104760

If you create two clocks, and set them both to the same time, you have two clocks.

If you change the time in one clock, it will not change the time in the other clock.

To compare or sort Dates, subtract one from the other. The valueof a Date object, used in a mathematical expression, is its timestamp.

function compareDates(a,b){return a-b};

Upvotes: 0

Alfabravo
Alfabravo

Reputation: 7569

Compare two dates with JavaScript

dates.compare(a,b)

The fact is that the comparison between the two objects does not work properly :/

Upvotes: 0

Related Questions