RSS Feed for This PostCurrent Article

java.sql.Timestamp compareTo bug in JDK 1.5 ?

If you run the following in code JDK1.5

java.util.Date dt1 = new Date();
java.util.Date dt2 = new java.sql.Timestamp(dt1.getTime());
if (dt2.compareTo(dt1) <= 0) {
    System.out.println("ok");
}

You will encounter the following error

java.lang.ClassCastException: java.util.Date
	at java.sql.Timestamp.compareTo(Timestamp.java:474)

but not the opposite

java.util.Date dt1 = new Date();
java.util.Date dt2 = new java.sql.Timestamp(dt1.getTime());
if (dt1.compareTo(dt2) <= 0) {
    System.out.println("ok");
}

I encountered this problem when I was migrating some Java code from JDK1.4 to JDK1.5. Image the line

java.util.Date dt2 = new java.sql.Timestamp(dt1.getTime());

is replaced with results from a JDBC ResultSet

java.util.Date dt2 = resultSet.getTimeStamp("dtField");

java.sql.Timestamp extends java.util.Date.

This problem does not happen in JDK1.4 and JDK1.6. It is only for JDK1.5. It is described here.

To resolve this issue, I changed the code to

java.util.Date dt1 = new Date();
java.util.Date dt2 = new java.sql.Timestamp(dt1.getTime());
if (dt2.getTime() <= dt1.getTime()) {
        System.out.println("Equal");
}

or

java.util.Date dt1 = new Date();
java.util.Date dt2 = new java.sql.Timestamp(dt1.getTime());
if (dt1.compareTo(dt2) <= 0) {
        System.out.println("Equal");
}


UPDATE: After upgrading to the latest JDK1.5 patch for the Unix server, the bug is fixed.


Trackback URL


RSS Feed for This Post1 Comment(s)

  1. Shikhar | Sep 18, 2009 | Reply

    Thanks this solved the mystery for me.

Sorry, comments for this entry are closed at this time.