前言
java 8 提供了一套新的時間 api ,比之前的 calendar 類要簡單明了很多。常用的有三個類 instant、localdate 、localdatetime , instant 是用來表示時刻的,類似 unix 的時間,表示從協調世界時1970年1月1日0時0分0秒起至現在的總秒數,也可以獲取毫秒。localdate 表示一個日期,只有年月日,沒有時分秒。localdatetime 就是年月日時分秒了。
下面話不多說了,來一起看看詳細的介紹吧
instant
1
2
3
4
5
|
public static void main(string[] args) { instant now = instant.now(); system.out.println( "now secoonds:" + now.getepochsecond()); system.out.println( "now milli :" + now.toepochmilli()); } |
輸出當前時刻距離 1970年1月1日0時0分0秒 的秒和毫秒
now secoonds:1541321299
now milli :1541321299037
localdatetime
為了方便輸出時間格式,java8 提供了 datetimeformatter 類來替代之前的 simpledateformat。
1
2
3
4
5
|
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 提供了很多時間計算的方法,比如 加一個小時,減去一周,加上一天等等這樣的計算,比之前的 calendar 要方便許多。
1
2
3
4
5
6
7
8
9
10
11
|
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 方法可以用來比較兩個時間。localdate 的用法和 localdatetime 是類似的。
instant 和 localdatetime 的互相轉換
這倆的互相轉換都要涉及到一個時區的問題。localdatetime 用的是系統默認時區。我們可以先把 localdatetime 轉為 zoneddatetime ,然后再轉成 instant。
1
2
3
4
5
6
7
8
|
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
1
2
3
4
5
6
7
8
9
10
|
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)); } |
now mini seconds: 1541323844781
zone id: asia/shanghai
now: 2018-11-04 17:30:44
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://juejin.im/post/5bdebd3ee51d4576452d224f