1. 程式人生 > >java8 中OffsetDateTime 和ZonedDateTime 的區別以及OffsetDateTime應該在寫入日期到資料庫時使用

java8 中OffsetDateTime 和ZonedDateTime 的區別以及OffsetDateTime應該在寫入日期到資料庫時使用

對幾種不同的日期進行列印

import java.time.*;

/**
 * @Author sunweipeng
 * @Date 2018/9/26 下午5:00
 * @Version 1.0
 **/
public class HelloWorld {
    public static void main(String[] args){
        System.out.println(LocalDateTime.now());
        System.out.println(Instant.now());
        System.out.println(OffsetDateTime.
now()); System.out.println(ZonedDateTime.now()); } }

打印出的結果如下:

2018-09-26T19:55:01.189
2018-09-26T11:55:01.190Z
2018-09-26T19:55:01.209+08:00
2018-09-26T19:55:01.210+08:00[Asia/Shanghai]

引用javadoc中的介紹

OffsetDateTime, ZonedDateTime and Instant all store an instant on the time-line to nanosecond precision. Instant is the simplest, simply representing the instant. OffsetDateTime adds to the instant the offset from UTC/Greenwich, which allows the local date-time to be obtained. ZonedDateTime adds full time-zone rules.

從上段說明知道OffsetDateTime和ZonedDateTime之間的差異在於後者包括涵蓋夏令時調整的規則。

It is intended that ZonedDateTime or Instant is used to model data in simpler applications. This class may be used when modeling date-time concepts in more detail, or when communicating to a database or in a network protocol.

至於為什麼在寫資料庫是採用OffsetDateTime

One reason is that dates with local time offsets always represent the same instants in time, and therefore have a stable ordering. By contrast, the meaning of dates with full timezone information is unstable in the face of adjustments to the rules for the respective timezones. (And these do happen…)

Dates whose meaning / ordering is unstable are problematic if (for example) you create a database index on a field the date.