2

我尝试使用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");

    }
}
4

3 回答 3

3

您在此处执行两种不同的操作:

Period p = Period.between(d1, d2)

为您提供了一种格式良好的方式来输出这些日期之间的差异(您已正确使用了格式选项)。

d1.until(d2, ChronoUnit.DAYS) 

会给你同样的 - 但不是很好的格式(基本上它只是给你 LocalDates 之间的天数)。

于 2017-08-27T13:13:24.360 回答
1

您不能像以前那样在计算天数差异时划分期间,因为期间计算取决于相关日期的月/年。在你的例子中,

2014 年 2 月14 日3 月 1日期间只有15 天

而 2017 年 2 月 14 日至 8 月 1 日之间的天数是从 2017 年 7 月 14 日至2017 年 8 月 1 日计算18天详细信息:

1) 14/02/2014 -> 14/02/2017: 3 years
2) 14/02/2017 -> 14/07/2017: 5 months
3) 14/07/2017 -> 01/08/2017: 18 days

这意味着将2017 年 8 月替换为2014 年3 月以独立于整个日期计算天数差异将导致不准确的答案(15而应该是18 天)。

因此,如果您正在执行任何手动计算而不仅仅是其day部分,或者只是简单而安全地使用Period类给定方法来执行所需的日期计算,您可能必须考虑整个日期。

于 2020-04-15T20:33:35.380 回答
1

答案(2014-02-14 和 2017-08-01 之间的时间是 3 年 5 个月 18 天)是您应该期待的:

  • 2014-02-14到3 年2017-02-14
  • 2017-02-14从到5 个月2017-07-14
  • 2017-07-14到18 天2017-08-01

计算从几年到几个月到几天。这使您可以计算 和 之间的年数、月数和天数2014-02-142016-02-29即 2 年零 15 天。

如果您尝试先计算天数,则在确定 和 之间的年数、月数和天数时会遇到问题2014-02-142016-02-29因为没有天2014-02-29- 在 之后 14 天,在之后2014-02-14152014-02-28天。2014-02-142014-03-01

于 2017-08-27T13:56:15.243 回答