С выпуском Java SE 8 в марте 2014 года устаревший и подверженный ошибкам устаревший API даты и времени (java.util типы даты и времени и тип их форматирования, SimpleDateFormat и т.д.) был заменен java.time современным API даты и времени *. В следующей таблице показано сопоставление типов ANSI SQL с java.time типами:
ANSI SQL
Java SE 8
Дата
LocalDate
ВРЕМЯ
LocalTime
МЕТКА ВРЕМЕНИ
LocalDateTime
ВРЕМЯ С ЧАСОВЫМ ПОЯСОМ
OffsetTime
МЕТКА ВРЕМЕНИ С ЧАСОВЫМ ПОЯСОМ
OffsetDateTime
Обратите внимание, что ZonedDateTime и Instant не поддерживаются ни одним драйвером JDBC, тогда как некоторые драйверы, например PostgreSQL, также не поддерживают OffsetTime / TIME [ WITHOUT TIMEZONE ]. Также обратите внимание, что все OffsetDateTime экземпляры должны быть в UTC (иметь смещение 0). Это потому, что серверная часть хранит их как UTC.
Как использовать это в JDBC?
Ниже приведен пример кода для вставки текущего значения OffsetDateTime в UTC, в columnfoo (который имеет TIMESTAMP WITH TIMEZONE тип):
An Instant представляет мгновенную точку на временной шкале и не зависит от часового пояса, т. е. Имеет смещение часового пояса на +00:00 часы.
Ниже приведен пример кода для извлечения OffsetDateTime из columnfoo:
Statementst= conn.createStatement(); ResultSetrs= st.executeQuery("SELECT * FROM mytable WHERE <some condition>"); while (rs.next()) { // Assuming the column index of columnfoo is 1 OffsetDateTimeodt= rs.getObject(1, OffsetDateTime.class)); System.out.println(odt); } rs.close(); st.close();
На всякий случай, если вам нужно преобразовать OffsetDateTime в другой с другим смещением:
Есть несколько способов сделать это, но я в основном использую OffsetDateTime#withOffsetSameInstant, для преобразования OffsetDateTime в другой с другим смещением часового пояса, например
publicclassMain { publicstaticvoidmain(String[] args) { // A sample OffsetDateTime in UTC. OffsetDateTimeodt= Instant.now().atOffset(ZoneOffset.UTC); System.out.println(odt);
Некоторые моменты, связанные с приведенным выше кодом:
The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
The code converts odt into two instances of OffsetDateTime - each in a different way. The first instance is with a fixed timezone offset of +02:00 hours whereas the second one is with the timezone offset of the JVM. Note that the timezone offset of a place observing DST changes as per the summer/winter time. Therefore, if a place observes DST, instead of using a fixed timezone offset e.g. +02:00 hours; we should get it from the API.
My JVM's timezone is Europe/London and currently its offset is +01:00 hours.