I have two columns which store DateTime values in a MySql database,
When I try to get them from a ResultSet in Java there is no option:
getDateTime()
Should I use getDate()
or wouldn't that work?
Thanks in advance
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.
You can use ResultSet.getTimeStamp()
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With