54

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.

mservidio
  • 12,817
  • 9
  • 58
  • 84

6 Answers6

72

The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

java.util.Date newDate = result.getTimestamp("VALUEDATE");
x4u
  • 13,877
  • 6
  • 48
  • 58
  • 3
    I'll try this then: new Date(result.getTimestamp("VALUEDATE").getTime()); – mservidio May 20 '11 at 00:48
  • 1
    this should work, but since `java.sql.Timestamp` also derives from `java.util.Date` you could as well just use the Timestamp instance. – x4u May 20 '11 at 00:53
20

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.

Farvardin
  • 5,336
  • 5
  • 33
  • 54
brianbruff
  • 2,092
  • 2
  • 14
  • 14
  • @PlexQ : It should if your sqlDate is null, but perhaps I'm missing something obvious as you appear to have used a lot of exclamation marks. – brianbruff Jun 03 '21 at 14:22
9

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

java.util.Date newDate = result.getDate("VALUEDATE");
doelleri
  • 19,232
  • 5
  • 61
  • 65
Bala R
  • 107,317
  • 23
  • 199
  • 210
7

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;
    }
ejvk
  • 5
  • 2
4

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
-2

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

Stanley Shi
  • 679
  • 1
  • 5
  • 9