20060523 Tuesday May 23, 2006

Comparing Timestamp and Date

Ran into this interesting little bug the other day:

Exception in thread "main" java.lang.ClassCastException: java.util.Date
        at java.sql.Timestamp.compareTo ...

Info can be found below:

http://bugs.sun.com/bugdatabase/view_bug.do;:YfiG?bug_id=6207898

Basically, with Java 1.5, you cannot always compare a Timestamp to a Date, even though a Timestamp is a Date.

Thus given

java.util.Date date = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp()

The following may throw and exception:

timestamp.compareTo(date)

The workaround is to call the compareTo method on the the Date object instead.

date.compareTo(timestamp)

Of course the result will be the opposite of what you originally intented, but as long as you realize this you can work around it.

Posted by rickg ( May 23 2006, 01:35:34 AM PDT ) Permalink Comments [0]