如何在兩個 Java LocalDate 之間獲取天數、月份和年份?


設定兩個 Java 日期

LocalDate date1 = LocalDate.of(2019, 3, 25);
LocalDate date2 = LocalDate.of(2019, 4, 29);

現在,使用 Period 類的 between() 方法,獲取兩個日期之間的差異

Period p = Period.between(date1, date2);

現在,獲取年份、月份和日期

p.getYears()
p.getMonths()
p.getDays()

示例

import java.time.LocalDate;
import java.time.Period;
public class Demo {
   public static void main(String[] args) {
      LocalDate date1 = LocalDate.of(2019, 3, 25);
      LocalDate date2 = LocalDate.of(2019, 4, 29);
      System.out.println("Date 1 = "+date1);
      System.out.println("Date 2 = "+date2);
      Period p = Period.between(date1, date2);
      System.out.println("Period = "+p);
      System.out.println("Years (Difference) = "+p.getYears());
      System.out.println("Month (Difference) = "+p.getMonths());
      System.out.println("Days (Difference) = "+p.getDays());
   }
}

輸出

Date 1 = 2019-03-25
Date 2 = 2019-04-29
Period = P1M4D
Years (Difference) = 0
Month (Difference) = 1
Days (Difference) = 4

更新時間:2019-07-30

894 次檢視

開啟你的職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.