我尝试使用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");
}
}
您在这里执行两个不同的操作:
Period p = Period.between(d1, d2)
为您提供了一种格式良好的方式来输出这些日期之间的差异(您已正确使用格式选项)。
d1.until(d2, ChronoUnit.DAYS)
会给你相同的 - 但格式不太好(基本上它只是给你本地日期之间的天数)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)