JAVA中的時間與日期——瞬時(Instant)
瞬時(Instant):
Instant:時間線上的一個瞬時點, 這可能被用來記錄應用程式中的事件時間戳,
在處理時間和日期的時候,我們通常會想到年,月,日,時,分,秒,然而,這只是時間的一個模型,是面向人類的,第二種通用模型是面向機器的,或者說是連續的,在此模型中,時間線中的一個點表示為一個很大的數,這有利于計算機處理,在UNIX中,這個數從1970年開始,以秒為的單位;同樣的,在Java中,也是從1970年開始,但以毫秒為單位,
java.time包通過值型別Instant提供機器視圖,不提供處理人類意義上的時間單位,Instant表示時間線上的一點,而不需要任何背景關系資訊,例如,時區,概念上講,它只是簡單的表示自1970年1月1日0時0分0秒(UTC)開始的秒數,因為java.time包是基于納秒計算的,所以Instant的精度可以達到納秒級,
(1 ns = 10-9 s) 1秒 = 1000毫秒 =106微秒=109納秒
常用方法介紹
①now() 靜態方法,回傳默認UTC時區的Instant類的物件
②ofEpochMilli(long epochMilli) 靜態方法,回傳在1970-01-01 00:00:00基礎上加上指定毫秒數之后的Instant類的物件
③atOffset(ZoneOffset offset) 結合即時的偏移來創建一個 OffsetDateTime
④toEpochMilli() 回傳1970-01-01 00:00:00到當前時間的毫秒數,即為時間戳
時間戳是指格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現在的總秒數,
代碼分步決議
public class InstantTest {
@Test
public void test1(){
Instant instant = Instant.now();//獲取本初子午線時間
System.out.println(instant+"\n");
運行結果:

如果想獲取北京時間怎么辦呢?則需用另一個方法atOffset(ZoneOffset offset)添加一個時間偏移量
//結合即時的偏移來創建一個 OffsetDateTime;添加時間偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime+"\n");
運行結果:

為啥偏移量是8小時呢,請看下圖,因為北京所處的時區在東八區,所以加了8小時,

前面有提到,在處理時間和日期的時候,在Java中,是從1970年開始,以毫秒為單位,如何獲取1970-01-01 00:00:00到當前時間的毫秒數?請用toEpochMilli()方法,
//獲取1970-01-01 00:00:00到當前時間的毫秒數,即為時間戳
long milli = instant.toEpochMilli();
System.out.println(milli+"\n");
運行結果:

最后一個常用方法:ofEpochMilli(long epochMilli) 靜態方法,回傳在1970-01-01 00:00:00基礎上加上指定毫秒數之后的Instant類的物件
//給定特定的毫秒數,獲取Instant實體
Instant instant1 = Instant.ofEpochMilli((1617760900204L));
System.out.println(instant1);
OffsetDateTime offsetDateTime1 = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime1+"\n");
運行結果:

也要通過加時間偏移量來獲取北京時間,
完整代碼:
public class InstantTest {
@Test
public void test1(){
Instant instant = Instant.now();//獲取本初子午線時間
System.out.println(instant+"\n");
//結合即時的偏移來創建一個 OffsetDateTime;添加時間偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime+"\n");
//獲取1970-01-01 00:00:00到當前時間的毫秒數,即為時間戳
long milli = instant.toEpochMilli();
System.out.println(milli+"\n");
//給定特定的毫秒數,獲取Instant實體
Instant instant1 = Instant.ofEpochMilli((1617760900204L));
System.out.println(instant1);
OffsetDateTime offsetDateTime1 = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime1+"\n");
//給定特定的秒數,獲取Instant實體
Instant instant2 = Instant.ofEpochSecond(instant.getEpochSecond());
System.out.println(instant2+"\n");
}
}
運行結果圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/273616.html
標籤:其他
上一篇:C語言實作BMP影像的移動
