Java 8 新增關于日期的操作類权悟,Instant 和 DateTime
Instant和 DateTime用于替換 Calender 和 Date。
官方說法是提供了更好的性能和一致性(線程安全)峻呕。
程序中有自己編寫的DateUtils工具類,計劃用Java8新提供的類替換之铭乾。
學習過程中遇到一些問題和感想璧微,記錄之。仔細考慮Instant類坑质,是一個時間點的抽象合武。
時間 和 時間刻度
程序模型是現(xiàn)實的模擬临梗,既然基于現(xiàn)實涡扼,則必須了解時間和時間刻度,他們產生的原因盟庞,是什么內容吃沪,以及如何產生(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)計時規(guī)則:
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 組成的只有兩個字段,秒 和 納秒:
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 本身只有時間點噪服,沒有時區(qū)信息毡泻,用 .atZone(ZoneId.systemDefault())
帶上本地時區(qū)信息即可。