2017-06-21 JDK8时间模型——Instant

Java 8 新增关于日期的操作类,Instant 和 DateTime

Instant和 DateTime用于替换 Calender 和 Date。
官方说法是提供了更好的性能和一致性(线程安全)。

程序中有自己编写的DateUtils工具类,计划用Java8新提供的类替换之。

学习过程中遇到一些问题和感想,记录之。仔细考虑Instant类,是一个时间点的抽象。

时间 和 时间刻度

程序模型是现实的模拟,既然基于现实,则必须了解时间和时间刻度,他们产生的原因,是什么内容,以及如何产生(why,what,how)。

直接引用 JDK Instant类的 java doc:

The length of the solar day is the standard way that humans measure time.

This has traditionally been subdivided into 24 hours of 60 minutes 
of 60 seconds, forming a 86400 second day.

Modern timekeeping is based on atomic clocks which precisely define an SI 
second relative to the transitions of a Caesium atom. The length of an SI 
second was defined to be very close to the 86400th fraction of a day.
...

大概就是这样,能理解就可以,然后Java 自己有自己的简化模型。

Java Time-Scale 时间刻度

首先是氛围两段(Segment)计时规则:

There are currently, as of 2013, two segments in the Java time-scale.

For the segment from 1972-11-03 (exact boundary discussed below) until
further notice, the consensus international time scale is UTC (with
leap seconds).  
...
On days that do have a leap second, the leap second is spread equally
over the last 1000 seconds of the day, maintaining the appearance of
exactly 86400 seconds per day.

For the segment prior to 1972-11-03, extending back arbitrarily far,
the consensus international time scale is defined to be UT1
...
In this segment, the Java Time-Scale is
identical to the consensus international time scale. 

The exact boundary between the two segments is the instant where UT1 = UTC
between 1972-11-03T00:00 and 1972-11-04T12:00.

然后是 Java Time-Scale 包含的类:

The Java time-scale is used for all date-time classes.
 This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime},
  {@code ZonedDateTime} and {@code Duration}.

终于到主题 Instant

两部分组成,表示秒的long,表示纳秒的int。
0秒表示1970-01-01,之前的用负秒,之后的用正秒。

当前时间 用的 Clock类的方法获得:

public static Instant now() { return Clock.systemUTC().instant(); }

Instant 组成的只有两个字段,秒 和 纳秒:


2017-06-21 JDK8时间模型——Instant_第1张图片
Instant fields

Instant 和 Date互转

Date转Instant:Instant instant = date.toInstant();
Instant转Date:Date date = Date.from(instant);

Instant 和 LocalDateTime互转

Instant转LocalDateTime:LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
LocalDateTime转Instant :Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

Instant Tips:

Instant 本身只有时间点,没有时区信息,用 .atZone(ZoneId.systemDefault()) 带上本地时区信息即可。

你可能感兴趣的:(2017-06-21 JDK8时间模型——Instant)