Jdbc ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp
Retrieve the full date and time from JDBC's ResultSet
using the getTimestamp()
method. This outputs java.sql.Timestamp
. For Java 8 and onwards, convert it to a LocalDateTime
:
This brief solution provides precise date-time, neatly packed for immediate use.
Going the full nine yards with getTimestamp()
When using getTimestamp()
to fetch date and time, you get invaluable nanosecond precision. Always remember to check for null
values before working with the fetched data:
Once the value has been retrieved, you may need to format it for display. Java 8's DateTimeFormatter
is your ally here:
A compressed guide to JDBC and date-time types
When interfacing JDBC and date-time types, there are some golden rules to keep in mind.
Direct exchange with JDBC 4.2 and java.time
JDBC 4.2 and above lets you directly exchange java.time
objects with the database using the handy setObject
and getObject
methods:
Sidestepping common traps
Avoid the potential inconsistencies of resultSet.getString()
for date-time values. It could append undesired fractions like ".0" to your time data. It's safer to stick with getTimestamp()
.
Pre-Java 8, consider ThreeTen-Backport
or Joda-Time
. These modern date-time classes offer familiar usability:
Call in SQL-side formatting when necessary
While not ideal, SQL's DATE_FORMAT
function can be a lifesaver, especially when you need the database to return neatly formatted date-time values:
Retrieve in Java as follows:
When in doubt, rigorously test
To round it off, thorough testing is essential. Date-time handling can vary significantly among databases and JDBC drivers. So, buckle up and conduct comprehensive testing. You wouldn't want any surprises when working with multiple databases or planning a migration.
Was this article helpful?