📅  最后修改于: 2023-12-03 15:31:54.873000             🧑  作者: Mango
在Java中,Period类表示两个日期之间的差异。它可以表示年份,月份和天数之间的差异。Period类提供了许多方法来计算两个日期之间的差异。其中之一是between()方法。
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
下面是一个示例演示如何使用between()方法计算两个日期之间的差异:
import java.time.LocalDate;
import java.time.Period;
public class PeriodExample {
public static void main(String[] args) {
// 计算两个日期之间的差异
LocalDate startDate = LocalDate.of(2020, 1, 1);
LocalDate endDate = LocalDate.of(2021, 10, 20);
Period period = Period.between(startDate, endDate);
System.out.println("Difference between " + startDate + " and " + endDate + ": " + period);
// 计算出两个日期之间的年数
int years = period.getYears();
System.out.println("Years between " + startDate + " and " + endDate + ": " + years);
// 计算出两个日期之间的月数
int months = period.getMonths();
System.out.println("Months between " + startDate + " and " + endDate + ": " + months);
// 计算出两个日期之间的天数
int days = period.getDays();
System.out.println("Days between " + startDate + " and " + endDate + ": " + days);
}
}
输出结果:
Difference between 2020-01-01 and 2021-10-20: P1Y9M19D
Years between 2020-01-01 and 2021-10-20: 1
Months between 2020-01-01 and 2021-10-20: 9
Days between 2020-01-01 and 2021-10-20: 19
在上面的示例中,我们首先创建了两个LocalDate对象,然后使用between()方法计算它们之间的差异。这将返回一个Period对象,它表示两个日期之间的差异。我们可以使用getYears()、getMonths()和getDays()方法获取年份、月份和天数之间的差异。