如何获得两个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-25Date 2 = 2019-04-29
Period = P1M4D
Years (Difference) = 0
Month (Difference) = 1
Days (Difference) = 4
以上是 如何获得两个Java LocalDate之间的天,月和年? 的全部内容, 来源链接: utcz.com/z/334775.html