[java] Converting java.sql.Date to java.util.Date

What's the simplest way to convert a java.sql.Date object to a java.util.Date while retaining the timestamp?

I tried:

java.util.Date newDate = new Date(result.getDate("VALUEDATE").getTime());

with no luck. It's still only storing the date portion into the variable.

This question is related to java jdbc

The answer is


Since java.sql.Date extends java.util.Date, you should be able to do

java.util.Date newDate = result.getDate("VALUEDATE");

From reading the source code, if a java.sql.Date does actually have time information, calling getTime() will return a value that includes the time information.

If that is not working, then the information is not in the java.sql.Date object. I expect that the JDBC drivers or the database is (in effect) zeroing the time component ... or the information wasn't there in the first place.

I think you should be using java.sql.Timestamp and the corresponding resultset methods, and the corresponding SQL type.


In the recent implementation, java.sql.Data is an subclass of java.util.Date, so no converting needed. see here: https://docs.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html


This function will return a converted java date from SQL date object.

public static java.util.Date convertFromSQLDateToJAVADate(
            java.sql.Date sqlDate) {
        java.util.Date javaDate = null;
        if (sqlDate != null) {
            javaDate = new Date(sqlDate.getTime());
        }
        return javaDate;
    }

If you really want the runtime type to be util.Date then just do this:

java.util.Date utilDate = new java.util.Date(sqlDate.getTime());

Brian.