I want to store a LocalDate
in a DATE
column and retrieve it unchanged. Both DATE
and LocalDate
are \"local\" types by de
The following solution also works. I prefer the conversion via String
in the accepted answer, because it avoids the timezone tinkering shown below. It may however not work the same way on all databases because some, e.g. Oracle, have a different definition of DATE
.
static LocalDate retrieve(DataSource ds) throws SQLException {
try (Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM people limit 1")) {
if (rs.next()) {
ZoneId utc = ZoneId.of("UTC");
TimeZone z = TimeZone.getTimeZone(utc);
Calendar cal = Calendar.getInstance(z);
java.sql.Date retrieved = rs.getDate("born", cal);
long time = retrieved.getTime();
java.util.Date utilDate = new java.util.Date(time);
Instant instant = utilDate.toInstant();
ZonedDateTime zdt = instant.atZone(utc);
return zdt.toLocalDate();
}
}
throw new IllegalStateException("No data");
}
The conversion via java.util.Date
is outlined in this question, as suggested by user Tunaki: Missed opportunity to fix JDBC date handling in Java 8?
I just tried the following modification to your retrieve
method and it worked for me:
The H2 documentation for the DATE Type says that it is
The date data type. The format is yyyy-MM-dd.
So, instead of your ...
java.sql.Date retrieved = (java.sql.Date) rs.getObject("born");
return retrieved.toLocalDate();
... I just used ...
return LocalDate.parse(rs.getString("born"));
... and my code produced
Inserted: 2015-05-20
Retrieved: 2015-05-20
Retrieved: 2015-05-20
Retrieved: 2015-05-20