21

Possible Duplicate:
Compare 2 dates with JavaScript

I haven't done much JavaScript. I am trying to compare two dates. From jconsole:

a = ["01/01/2010","01/02/2010","01/03/2010"]

date1 = new Date('01/02/2010')
Sat Jan 02 2010 00:00:00 GMT-0800 (PST)

date2 = new Date(a[1])
Sat Jan 02 2010 00:00:00 GMT-0800 (PST)

date1 == date2
false

Can someone tell me why this does not match?

1
  • 7
    It is interesting to note that both >= and <= return true in this case, but == gives false. Another JavaScript miracle. Commented May 2, 2010 at 5:37

1 Answer 1

38

Your comparison is returning false because date1 and date2 are simply references to different objects, and you are actually comparing these references.

To do a proper comparison of the date values, you can use the getTime() method as follows:

date1.getTime() === date2.getTime();   // returns true
Sign up to request clarification or add additional context in comments.

2 Comments

okay thanks. So '===' also compares type. Do '<=' and '>=' also compare type?
@ash34: Yes it is generally recommended to use === instead of ==. You may also want to check out this reference: developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…. First of all note the part where it says: "Two objects are strictly equal if they refer to the same Object."... Also check the description of the different comparison operators.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.