Comparing of Date objects in Java

compareto, date, equals, java

Solution

I guess they are not both Date objects as the formatting is different.

java.sql.Timestamp extends java.util.Date but it is a different class and is not equal.

From Timestamp

public boolean equals(java.lang.Object ts) {
  if (ts instanceof Timestamp) {
    return this.equals((Timestamp)ts);
  } else {
    return false;
  }
}

You might find that if you compare them the other way around it returns true. :P

try

logger.debug("Dates are equal: " + other.getDate().equals(this.getDate()));

Problem

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)

Original source