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.

该问题的原地址:https://stackoverflow.com/questions/30234594/whats-the-difference-between-java-8-zoneddatetime-and-offsetdatetime

你可能感兴趣的:(java,8)