Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 871
Art Avatar asked May 22 '10 16:05

Art


People also ask

Can you compare JavaScript dates?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

How can I compare two dates?

For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 2.


1 Answers

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.

like image 62
Sean Kinsey Avatar answered Oct 19 '22 18:10

Sean Kinsey