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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With