Date and time
The PostgreSQL® JDBC driver implements native support for the Java 8 Date and Time API (JSR-310) using JDBC 4.2.
Table 5.1. Supported Java 8 Date and Time classes
| PostgreSQL® | Java SE 8 |
|---|---|
| DATE | LocalDate |
| TIME [ WITHOUT TIME ZONE ] | LocalTime |
| TIME WITH TIME ZONE | OffsetTime |
| TIMESTAMP [ WITHOUT TIME ZONE ] | LocalDateTime |
| TIMESTAMP WITH TIME ZONE | OffsetDateTime |
This is closely aligned with tables B-4 and B-5 of the JDBC 4.2 specification.
Note
ZonedDateTimeandInstantare not supported. Also note thatOffsetDateTimeinstances forTIMESTAMP WITH TIME ZONEare returned in UTC (offset 0). This is because the backend stores them as UTC.
Example 5.2. Reading Java 8 Date and Time values using JDBC
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
while (rs.next()) {
System.out.print("Column 1 returned ");
LocalDate localDate = rs.getObject(1, LocalDate.class);
System.out.println(localDate);
}
rs.close();
st.close();
For other data types simply pass other classes to #getObject.
Note
The Java data types need to match the SQL data types in Table 5.1.
Example 5.3. Writing Java 8 Date and Time values using JDBC
LocalDate localDate = LocalDate.now();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, localDate);
st.executeUpdate();
st.close();