When I test this code:
java.util.Date date = new java.util.Date();
java.util.Date stamp = new java.sql.Timestamp(date.getTime());
assertTrue(date.equals(stamp));
assertTrue(date.compareTo(stamp) == 0);
assertTrue(stamp.compareTo(date) == 0);
assertTrue(stamp.equals(date));
I´ll be expecting a true, true, true, false. Because of this:
In the javadoc for java.sql.Timestamp, it states:
Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate. The Timestamp.equals(Object) method never returns true when passed a value of type java.util.Date because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashcode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.
But instead I´ll get a true, false, true, false. Any ideas?
EDIT: This problem appear when a I was checking two Dates with the equals method, but one of the Date object come from a Hibernate class and debugging I see that the object contains a TimeStamp. So the equals method evaluate to false, then I found this: http://mattfleming.com/node/141
But when I try the code I get different results...if I can´t use neither equals and compareTo, what I should use to check if 2 Dates are the same?!?!
Timestamp
is silly; you should treat those two classes as not being related, as was the intention of whoever wrote it. – Bartolome