欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java8 Instant 時(shí)間戳實(shí)例講解

 更新時(shí)間:2022年11月04日 14:59:55   作者:springinwinter_4all  
Instant類是Java8 中補(bǔ)充的一個(gè) 時(shí)間戳類,nstant 可以使用靜態(tài)方法 now()或者of()方法來創(chuàng)建一個(gè)實(shí)例對(duì)象,本文通過實(shí)例代碼講解Java8 Instant 時(shí)間戳,感興趣的朋友跟隨小編一起看看吧

說明

Instant 類  是Java8 中補(bǔ)充的一個(gè) 時(shí)間戳類。
相較于 System.currentTimeMillis()獲取到【毫秒】,Instant 可以更為精確的獲取到【納秒】。

Instant 可以使用靜態(tài)方法 now() 或者 of() 方法來創(chuàng)建一個(gè)實(shí)例對(duì)象。(案例代碼中會(huì)有體現(xiàn))

Instant 類的常用API 就是獲取時(shí)間戳了
 * Instant 類的 getEpochSecond() : 獲取的是秒
 * Instant 類的 toEpochMilli() : 獲取的是毫秒,同 System.currentTimeMillis()
 * Instant 類的 getNano() : 獲取的是納秒,更精確了

同時(shí),Instant 類還是 Java8 中 提供的新的 日期時(shí)間類LocalDateTime 與 原來的 java.util.Date 類之間轉(zhuǎn)換的橋梁。

在java.util.Date類與LocalDate、LocalDateTime類之間轉(zhuǎn)換中 均可以通過Instant作為中間類完成轉(zhuǎn)換,Instant的使用還是比較方便的,下面介紹Instant的使用。

一、創(chuàng)建Instant實(shí)例

Instant now = Instant.now();
System.out.println("now:"+now);

控制臺(tái)輸出:

now:2018-07-09T08:59:08.853Z

注意:通過這種方式獲取的時(shí)間戳與北京時(shí)間相差8個(gè)時(shí)區(qū),需要修正為北京時(shí)間,通過查看源代碼發(fā)現(xiàn)Instant.now()使用等是UTC時(shí)間Clock.systemUTC().instant()。LocalDate、LocalDateTime 的now()方法使用的是系統(tǒng)默認(rèn)時(shí)區(qū) 不存在Instant.now()的時(shí)間問題。
###解決方法
增加8個(gè)小時(shí)

Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
System.out.println("now:"+now);

控制臺(tái)輸出:

now:2018-07-09T16:58:48.188Z

二、Instant獲取long類型的10位秒數(shù)、13位毫秒數(shù)

Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
System.out.println("秒數(shù):"+now.getEpochSecond());
System.out.println("毫秒數(shù):"+now.toEpochMilli());

控制臺(tái)輸出:

秒數(shù):1539170157
毫秒數(shù):1539170157886

LocalDateTime輸出毫秒數(shù)的方式,比Instant多一步轉(zhuǎn)換

LocalDateTime localDateTime = LocalDateTime.now();
//LocalDateTime轉(zhuǎn)Instant
Instant localDateTime2Instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println("LocalDateTime 毫秒數(shù):"+localDateTime2Instant.toEpochMilli());

控制臺(tái)輸出:

LocalDateTime 毫秒數(shù):1539141733010

到此這篇關(guān)于Java8 Instant 時(shí)間戳的文章就介紹到這了,更多相關(guān)Java8 Instant 時(shí)間戳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論