Search code examples
javascriptdate-comparison

Compare javascript dates


I'm comparing dates with something like this:

var dt = new Date();    

dt.setDate("17");               
dt.setMonth(06); 
dt.setYear("2009");

var date = new Date();

console.log("dt(%s) == date(%s) == (%s)", dt, date, (dt == date) );

if( now == dt ) {
    ....
}

The string values are dynamic of course.

In the logs I see:

dt(Fri Jul 17 2009 18:36:56 GMT-0500 (CST)) == date(Fri Jul 17 2009 18:36:56 GMT-0500 (CST) == (false)

I tried .equals() but it didn't work ( I was trying the Java part of JavaScript :P )

How can I compare these dates so they return true?


Solution

  • The following code should solve your problem:

    (myDate.getTime() == myOtherDate.getTime())
    

    The problem is that when you write:

    (myDate == myOtherDate)
    

    ...you're actually asking "Is myDate pointing to the same object that myOtherDate is pointing to?", not "Is myDate identical to myOtherDate?".

    The solution is to use getTime to obtain a number representing the Date object (and since getTime returns the number of milliseconds since epoch time, this number will be an exact representation of the Date object) and then use this number for the comparison (comparing numbers will work as expected).