Java中的Period类的between()方法用于获取一个包含两个给定日期(包括开始日期和结束日期)之间的年,月和天数的时间段。
获得此时间段的方式如下:
删除完整的月份。
现在,计算剩余天数。
然后,调整以确保两者具有相同的符号。
现在,根据12个月的年份将月份数分为年份和月份。
如果结束day-of-month大于或等于开始day-of-month,请考虑一个月(例如:从2017-05-12到2018-07-18为一年零两个月零六天)。
注意:如果结束时间早于开始时间,则根据上述公式获得的时间段可以为负。负号在每年,每月和每天中都相同。
用法:
public static Period between(LocalDate startDateInclusive,
LocalDate endDateExclusive)
参数:
startDateInclusive –开始日期包括在内,并且不能为null。
endDateExclusive –结束日期是排他的,并且不能为null。
返回值:period的between()函数返回给定开始日期和结束日期之间的时间段。
下面是上述功能的实现:
// Java code to show the period
// between given start and end date
import java.time.LocalDate;
import java.time.Period;
public class PeriodClass {
// Function to calculate period between
// start and end date
static void calculatePeriod(LocalDate startDate,
LocalDate endDate)
{
Period period = Period.between(startDate, endDate);
System.out.println("Period between start and end "
+ "date is : " + period);
}
// Driver Code
public static void main(String[] args)
{
// Start date
LocalDate startDate = LocalDate.parse("2017-02-13");
// End date
LocalDate endDate = LocalDate.parse("2018-08-20");
calculatePeriod(startDate, endDate);
}
}
输出:
Period between start and end date is : P1Y6M7D