Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two identical JavaScript dates aren't equal

Tags:

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

like image 240
Bryce Avatar asked Mar 18 '13 05:03

Bryce


People also ask

Why are two identical objects not equal to each other?

Objects are not compared by value: two objects are not equal even if they have the same properties and values. This is true of arrays too: even if they have the same values in the same order. Objects are sometimes called reference types to distinguish them from JavaScript's primitive types.

How do you compare two date objects in JavaScript?

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.

Are dates equal JavaScript?

The equality operator checks for reference equality. This means it only returns true if the two variables refer the the same object. If you create two Date objects ( var a = new Date(); var b = new Date(); ), they will never be equal.

How do you find out if two dates are the same?

There are two ways to check if two dates are equal in Java : Date's equals() method - return true if two dates are equal. Date's compareTo() method - return zero if two dates are equal.


1 Answers

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 
like image 198
Bryce Avatar answered Oct 02 '22 20:10

Bryce