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

java8 Instant 時(shí)間及轉(zhuǎn)換操作

 更新時(shí)間:2020年09月17日 11:00:38   作者:stay hungry,stay you  
這篇文章主要介紹了java8 Instant 時(shí)間及轉(zhuǎn)換操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

一、獲取當(dāng)前時(shí)區(qū)時(shí)間:

Instant.now().atZone(ZoneId.systemDefault())

二、創(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

補(bǔ)充知識(shí):jdk8中獎(jiǎng)Date轉(zhuǎn)換為String格式的方法

我就廢話不多說了,大家還是直接看代碼吧~

public static String getLocalDateStr(Date date,String formatter) {
	   
     DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);     
     Instant instant = date.toInstant();
     ZoneId zoneId = ZoneId.systemDefault();
     LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);   
     String dateStr = dateTimeFormatter.format(localDateTime);   	   
	   return dateStr;
   }

以上這篇java8 Instant 時(shí)間及轉(zhuǎn)換操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論