重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
這篇文章給大家介紹Java8中有哪些常用的時(shí)間api,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
Instant
public static void main(String[] args) { Instant now = Instant.now(); System.out.println("Now secoonds:" + now.getEpochSecond()); System.out.println("Now milli :" + now.toEpochMilli()); }
輸出當(dāng)前時(shí)刻距離 1970年1月1日0時(shí)0分0秒 的秒和毫秒
Now secoonds:1541321299
Now milli :1541321299037
LocalDateTime
為了方便輸出時(shí)間格式,Java8 提供了 DateTimeFormatter 類來替代之前的 SimpleDateFormat。
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); System.out.println("Now: " + now.format(formatter)); }
Now: 2018-11-04 16:53:09
LocalDateTime 提供了很多時(shí)間計(jì)算的方法,比如 加一個(gè)小時(shí),減去一周,加上一天等等這樣的計(jì)算,比之前的 Calendar 要方便許多。
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); System.out.println("Now: " + now.format(formatter)); LocalDateTime nowPlusDay = now.plusDays(1); System.out.println("Now + 1 day: " + nowPlusDay.format(formatter)); LocalDateTime nowMinusHours = now.minusHours(5); System.out.println("Now - 5 hours: " + nowMinusHours.format(formatter)); }
Now: 2018-11-04 17:02:53
Now + 1 day: 2018-11-05 17:02:53
Now - 5 hours: 2018-11-04 12:02:53
LocalDateTime 還有 isAfter 、 isBefore 和 isEqual 方法可以用來比較兩個(gè)時(shí)間。LocalDate 的用法和 LocalDateTime 是類似的。
Instant 和 LocalDateTime 的互相轉(zhuǎn)換
這倆的互相轉(zhuǎn)換都要涉及到一個(gè)時(shí)區(qū)的問題。LocalDateTime 用的是系統(tǒng)默認(rèn)時(shí)區(qū)。我們可以先把 LocalDateTime 轉(zhuǎn)為 ZonedDateTime ,然后再轉(zhuǎn)成 Instant。
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); System.out.println("Now: " + now.format(formatter)); Instant nowInstant = now.atZone(ZoneId.systemDefault()).toInstant(); System.out.println("Now mini seconds: " + nowInstant.toEpochMilli()); }
Now: 2018-11-04 17:19:16
Now mini seconds: 1541323156101
public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); Instant now = Instant.now(); System.out.println("Now mini seconds: " + now.toEpochMilli()); LocalDateTime nowDateTime = LocalDateTime.ofInstant(now, ZoneId.systemDefault()); System.out.println("Zone id: " + ZoneId.systemDefault().toString()); System.out.println("Now: " + nowDateTime.format(formatter)); }
關(guān)于Java8中有哪些常用的時(shí)間api就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。