JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

Tim picture Tim · Jan 16, 2014 · Viewed 115.6k times · Source

I would like to get the DATETIME column from an Oracle DB Table with JDBC. Here is my code:

int columnType = rsmd.getColumnType(i);
if(columnType == Types.DATE)
{
    Date aDate = rs.getDate(i);
    valueToInsert = aDate.toString();
}
else if(columnType == Types.TIMESTAMP)
{
    Timestamp aTimeStamp = rs.getTimestamp(i);
    valueToInsert = aTimeStamp.toString();
}
else
{
    valueToInsert = rs.getString(i);
}

I have to identify the column type first. The field I am interested in is recognized as a Types.DATE, but it is really a DATETIME in the DB since it has this format: "07.05.2009 13:49:32"

getDate truncates the time: "07.05.2009" and getString appends ".0" to it: "07.05.2009 13:49:32.0"

Of course I could just remove the final .0 and work with getString all the time, but it is a dirty workaround.

Any ideas ? I was looking for a getDateTime method.

Cheers, Tim

Answer

Leos Literak picture Leos Literak · Jan 16, 2014
java.util.Date date;
Timestamp timestamp = resultSet.getTimestamp(i);
if (timestamp != null)
    date = new java.util.Date(timestamp.getTime()));

Then format it the way you like.