Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
OscarRyz Avatar asked Dec 23 '22 10:12

OscarRyz


2 Answers

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).

like image 159
Steve Harrison Avatar answered Dec 27 '22 05:12

Steve Harrison


The problem with your code is that you are comparing time/date part instead of only the date.

Try this code:

    var myDate = new Date();
    myDate.setDate(17);
    myDate.setMonth(7);
    myDate.setYear(2009);

    //Delay code - start
    var total = 0;
    for(var i=0; i<10000;i++)
        total += i;
    //Delay code - end

    var now = new Date();

    console.log(now.getTime() == myDate.getTime());

If you keep the for loop code (identified by 'Delay code -start'), console will show 'false' and if you remove the for loop code, console will log 'true' even though in both the cases myDate is 7/17/2009 and 'now' is 7/17/2009.

The problem is that JavaScript date object stores both date and time. If you only want to compare the date part, you have to write the code.

function areDatesEqual(date1, date2)
{
    return date1.getFullYear() == date2.getFullYear() 
            && date1.getMonth() == date2.getMonth()
            && date1.getDate() == date2.getDate();
}

This function will print 'true' if the two javascript 'date part' is equal ignoring the associated time part.

like image 42
SolutionYogi Avatar answered Dec 27 '22 05:12

SolutionYogi