It's not a secret anymore!
The moose likes Java in General and the fly likes Comparing Dates and Timestamps Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparing Dates and Timestamps" Watch "Comparing Dates and Timestamps" New topic

Comparing Dates and Timestamps

Jay Damon
Ranch Hand

Joined: Jul 31, 2001
Posts: 282
I am currently engaged in a debate regarding the validity of comparing java.util.Date and java.sql.Timestamp objects. The Java API for Timestamp specifically limits methods compareTo and equals to the comparison of like objects, i.e. both must be Timestamps. However, it is possible to use the methods after and before inherited from Date to compare a Timestamp to a Date. IMO, doing so is not only sloppy coding but simply a bad idea. Just because it is legal does not mean it should be done. I believe these methods should only be used to compare a Date to a Date and a Timestamp to a Timestamp.

Comments, anyone?
pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547
the API states that equals() method must be symetric. Date.equals(Timestamp) or Timestamp.equals(Date) should always return false.
-> never use "instanceof" in your equals() implementation if you want to follow the API description.

Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

If somebody writes a class that isn't final, and they declare a method in that class, they should expect that people can write a subclass of the class and that people will then call methods of the superclass that haven't been overridden. The language expects that to happen. It's basic polymorphism. So in general it is neither sloppy nor a bad idea.

Now, it's possible that the process I described there will result in the superclass's method not working correctly for the subclass. If that happens then it's the responsibility of the subclass writer to override it so that it does work correctly. Or to have it throw an unchecked exception, or to document the failure. (In order of preference from best to worst.)

The option chosen by the writer of the Timestamp class was the third, namely to document the failure:

"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."
I agree. Here's the link:
subject: Comparing Dates and Timestamps
It's not a secret anymore!