• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing Dates and Timestamps

 
Jay Damon
Ranch Hand
Posts: 282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

pascal
 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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."
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic