我尝试使用java.time.Period
,结果与我手动计算的结果相差了三天。这里奇怪的是,当我将周期分为两个周期时,结果与我的手动计算相符。
第二种方法就像我手动计算周期一样。
有什么我错过的吗?是否有日历算术的标准方法或算法?使用的算法是java.time.Period
什么?
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class test2 {
public static void main(String[] args) {
LocalDate d1 = LocalDate.of(2014, 2, 14);
LocalDate d2 = LocalDate.of(2017, 8, 1);
Period p = Period.between(d1, d2);
//using period between the two dates directly
System.out.println("period between " + d1.toString() + " and " + d2.toString() + " is " + p.getYears()
+ " years " + p.getMonths() + " months " + p.getDays() + " Days");
//dividing the period into two parts
p = Period.between(LocalDate.of(2014, 3, 1), d2);
System.out
.println("period between " + d1.toString() + " and " + d2.toString() + " is " + p.getYears() + " years "
+ p.getMonths() + " months " + d1.until(LocalDate.of(2014, 3, 1), ChronoUnit.DAYS) + " Days");
}
}