2

this is my 1st question in stackoverflow.

var str="Oct 13,2011";
var date1=new Date(str);
var date2=new Date(str);

of course valueOf(date1)==valueOf(date2)

but why date1!=date2

or say,how to determine 2 date object if they equal each other.

Date is a js object

alex
  • 479,566
  • 201
  • 878
  • 984
NamiW
  • 1,572
  • 4
  • 19
  • 33

3 Answers3

5

Javascript objects are only equal if they refer to the same object-reference. Which is not the case in your code.

(reference: What is the standard definition of object equality for "=="?)

Edit: With a little type casting you can do:

var str="Oct 13,2011";
var date1 = new Date(str);
var date2 = new Date(str);

console.log(+date1 == +date2); // true
Community
  • 1
  • 1
Yoshi
  • 54,081
  • 14
  • 89
  • 103
2

== or === compares object references.

Date1 and date 2 are created from different references. Therefore, they are not equal.

convert your date1 and date2 to primitive data type and compare

date1.getTime()=== date2.getTime()

Result : True

TheOneTeam
  • 25,806
  • 45
  • 116
  • 158
1

Using == does not work in general as it compares object identities not values.

Using the + prefix or getTime() to convert to milliseconds before comparison can also fail in the case your date objects have a time component and you only wish to compare their date portions. (Do not be tempted to reach for the toDate() method as that is day of month, and discards month and year!).

This seems to be one of the few times that toDateString() is useful, for a succinct solution without the use of additional libraries.

var date1=new Date("2014-12-10");
var date2=new Date("2014-12-10T01:00");

+date1 == +date2
>false

date1.getTime() == date2.getTime()
>false

date1.toDateString() == date2.toDateString()
>true
Community
  • 1
  • 1
joth
  • 1,692
  • 1
  • 14
  • 6