getDateTime from ResultSet java
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.Date
and 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.