Compare javascript dates

I am 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 ) { .... } 

String values ​​are, of course, dynamic.

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 did not work (I tried to use the Java part of JavaScript: P)

How can I compare these dates so they come back?

+4
source share
3 answers

The following code should solve your problem:

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

The problem is that when you write:

 (myDate == myOtherDate) 

... you really ask: "Is myDate pointer to the same object that myOtherDate points to?", and not "Is myDate is identical to myOtherDate ?".

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

Steve

+8
source

The problem with your code is that you are comparing time / date, not just 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 save the loop cycle code (identified by the “Start-delay code”), the console will show “false”, and if you delete the loop cycle code, the console will write “true”, although in both cases myDate is 7/17/2009 and “now "- 7/17/2009.

The problem is that the JavaScript date object stores both date and time . If you want to compare only the date, you need to write 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 parts of the javascript date are equal, ignoring the associated time part.

+3
source
 => (myDate.getTime() == myOtherDate.getTime()) 

(myDate == myOtherDate) does not work, it compares two objects (pointers) instead of the value that they contain. Use getTime to get an integer representation of Date and then compare.

0
source

All Articles