getDateTime from ResultSet java

Using getDate() only returns a Date, so in your case if you want both date and time use getTimestamp(String columnLabel) - That should work, also replace String columnLabel with the actual column name in the database.


Prefer timestamp over datetime in MySQL

First, if the datetime in your database is to represent a point in time, use the timestamp datatype in MySQL for that, not datetime. A datetime is open for interpretation into any time zone the reader or the program reading it happens to use. This can lead to errors that are hard to debug. The timestamp datatype behaves differently in various RDBMSs. In MySQL it makes sure that dates and times are in UTC, thus excluding faulty interpretation into any other time zone. It’s safer. If the dates and times are a little harder for users in your own time zone to read in the database, it’s worth it.

java.time

    PreparedStatement ps = yourDatabaseConnection.prepareStatement("select your_datetime_col from your_table;");
    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            OffsetDateTime dateTime = rs.getObject("your_datetime_col", OffsetDateTime.class);
            // do something with dateTime
        }
    }

Use ResultSet.getObject() for retrieving date and time from the database into a type from java.time, the modern Java date and time API. The classes java.sql.Timestamp, java.sql.Dateand java.util.Date mentioned or implied in the question and the other answers are all poorly designed and long outdated, so I recommend the modern API instead. It requires a JDBC 4.2 compliant driver. Most of us have that, and one has been out for MySQL for very many years. SO I expect that you are fine.

If you cannot change the datatype in MySQL, use LocalDateTime in Java for retrieving values from your datatime column. It goes in the same way as in the code above.

To answer your concrete question

Should I use getDate() or wouldn't that work?

No it would not. getDate() gives you a java.sql.Date holding only the date part from the database, the time of day part will be missing. As I said, java.sql.Date is also poorly designed — a true hack on top of the already poorly designed java.util.Date — so you shouldn’t want that anyway.

Links

  • Java Best Practice for Date Manipulation/Storage for Geographically Diverse Users
  • My answer to Getting the date from a ResultSet for use with java.time classes
  • Oracle tutorial: Date Time explaining how to use java.time.

You can use ResultSet.getTimeStamp()


Or with a typecast from date to string:

resultSet.getDate(1).toString());

will return:

2014-02-18

DB field data: "2014-02-18 00:00:00.000"