I recently observed an oddity, when comparing two Java Date objects with equals(). Please note that both, this.getDate() and other.getDate(), will return a Java Date object in my application.
Code:
logger.debug("Date 1: " + this.getDate().toString());
logger.debug("Date 1: " + this.getDate().getTime());
logger.debug("Date 2: " + other.getDate().toString());
logger.debug("Date 2: " + other.getDate().getTime());
logger.debug("Dates are equal: " + this.getDate().equals(other.getDate()));
logger.debug("Dates match in comparison: " + (this.getDate().compareTo(other.getDate()) == 0));
Output: (added blank lines for better readability)
Date 1: 2014-07-28 00:00:00.0
Date 1: 1406498400000
Date 2: Mon Jul 28 00:00:00 CEST 2014
Date 2: 1406498400000
Dates are equal: false
Dates match in comparison: true
There are two things I don't get:
- Why does equals() return false?
- Why does the return value of toString() change its format?
I checked the documentation of Date.equals() where it says:
Compares two dates for equality. The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object.
Thus, two Date objects are equal if and only if the getTime method returns the same long value for both.
I also had a look at the implementation of Date.equals():
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
So why does equals() return false, even though getTime() returns 1406498400000 for both Date objects?
Reference: http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#equals(java.lang.Object)
Date()objects?getDatemethod is not doing what it would be expected to do. I think we should see it.