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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值