Today most of us are using JDBC 4.2 compliant drivers, which improves the situation quite a bit compared to the answers from 2015.
To get a LocalDate
from your result set:
LocalDate dateFromDatabase = yourResultSet.getObject(yourColumnIndex, LocalDate.class);
or
LocalDate dateFromDatabase = yourResultSet.getObject("yourColumnLabel", LocalDate.class);
No new method has been added to ResultSet
for this to work. The getObject
method was there all the time. The new thing is that since JDBC 4.2 it accepts LocalDate.class
as the second argument and returns a LocalDate
. The above works when the query returns a column with SQL datatype date
(really the JDBC type counts, but they tend to agree).
You can pass classes of other java.time types too. And get the corresponding type back. For example:
OffsetDateTime dateTimeFromDatabase
= yourResultSet.getObject(yourTimestampWithTimeZoneColumnIndex, OffsetDateTime.class);
The java.time types to use are:
SQL datatype | java.time type
------------------------+-----------------------------------------------------------
date | LocalDate
time | LocalTime
timestamp | LocalDateTime
timestamp with timezone | Officially OffsetDateTime; many drivers accept Instant too
time with timezone | OffsetTime
For passing the other way, from Java to your database (for use as query parameters or for storing) PreparedStatement.setObject
now accepts objects of the above java.time types too. Since you are passing an object of a type, there is no need for a separate type parameter when going this way.