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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With