Timestamp vs. Date on compareTo

I made another update to the JSPWiki JDBC Providers after a user was getting errors mixing the JDBC page provider with a different, non-JDBC attachment provider. The weird thing is that I have the same mixing in the wikis I maintain without any of those errors. Something must be different, but the error makes perfect sense, and so I fixed it.

Part of the page provider API includes a page info class with a date field of type java.util.Date. Getting my data from a SQL database, I was working with java.sql.Timestamp values, and since java.sql.Timestamp is derived from java.util.Date, it seemed to work OK just handing my java.sql.Timestamp value to the page info class. The problem occurs when the engine sorts pages by date, invoking compareTo() on the date values from two page info instances.

java.sql.Timestamp.compareTo() throws an exception if the argument is a java.util.Date (or anything other than a java.sql.Timestamp). It sounds reasonable since java.sql.Timestamp has more precision than a normal java.util.Date (nanoseconds vs. milliseconds), but is it really worth the hassle? I’d rather see the compare succeed by assuming 0 values for the missing precision.

The lesson may be to not rely on foreign compareTo() implementations. In this case, millisecond comparisons provide more than enough precision, so just write a compareTo() method for the page info class that converts the dates to milliseconds and returns the comparison of those values.

One Response to “Timestamp vs. Date on compareTo”

  1. Anli says:

    Just read Sun’s lame javadoc on Timestamp. Seems to me they were too lazy to implement it properly.

Leave a Reply