1. 程式人生 > 其它 >Java 8 時間類介紹

Java 8 時間類介紹

技術標籤:Java

Java 8 中新增了3個時間類:

名稱說明是否可變是否執行緒安全
LocalDate用於表示日期
LocalTime用於表示時間(時分秒)
LocalDateTime用於表示日期+時間

相關示例:

LocalDate

    //獲取當前日期
    LocalDate today = LocalDate.now();
    System.out.println("today : " + today);

    //獲取昨天日期
    LocalDate yesterday = today.minusDays(1);
    System.
out.println("yesterday : " + yesterday); //獲取明天日期 LocalDate tomorrow = today.plusDays(1); System.out.println("tomorrow : " + tomorrow); //構建日期 LocalDate someDay = LocalDate.of(2021, 1, 1); System.out.println("someDay : " + someDay); //計算日期相差天數 long
days = today.toEpochDay() - someDay.toEpochDay(); System.out.println("days : " + days);

輸出:

today : 2021-02-07
yesterday : 2021-02-06
tomorrow : 2021-02-08
someDay : 2021-01-01
days : 37

LocalDateTime

    //獲取當前時間
    LocalDateTime now = LocalDateTime.now();
    System.out.println("now : "
+ now); //獲取明日此時的時間 LocalDateTime tomorrow = now.plusDays(1); System.out.println("tomorrow : " + tomorrow); //獲取昨日此時的時間 LocalDateTime yesterday = now.minusDays(1); System.out.println("yesterday : " + yesterday); //日期判斷 if (now.isAfter(yesterday)) { System.out.println("now is after yesterday"); } if (now.isBefore(tomorrow)) { System.out.println("now is before tomorrow"); } //獲取明日的開始時間 LocalDateTime tomorrowBegin = LocalDateTime.of(tomorrow.toLocalDate(), LocalTime.MIN); System.out.println("tomorrowBegin : " + tomorrowBegin); //獲取明日的結束時間 LocalDateTime tomorrowEnd = LocalDateTime.of(tomorrow.toLocalDate(), LocalTime.MAX); System.out.println("tomorrowEnd : " + tomorrowEnd); //計算兩日期的時間差 Duration duration = Duration.between(now, tomorrowEnd); System.out.println("duration of now and tomorrowEnd by days : " + duration.toDays()); System.out.println("duration of now and tomorrowEnd by hours : " + duration.toHours());

輸出:

now : 2021-02-07T16:40:30.910
tomorrow : 2021-02-08T16:40:30.910
yesterday : 2021-02-06T16:40:30.910
now is after yesterday
now is before tomorrow
tomorrowBegin : 2021-02-08T00:00
tomorrowEnd : 2021-02-08T23:59:59.999999999
duration of now and tomorrowEnd by days : 1
duration of now and tomorrowEnd by hours : 31