【问题标题】:java.time.Period , dividing the period gives wrong resultsjava.time.Period ,划分期间会给出错误的结果
【发布时间】:2018-02-04 21:32:49
【问题描述】:

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

    }
}

【问题讨论】:

  • 你到底想做什么?你得到什么结果?你期待什么结果?

标签: java time period localdate


【解决方案1】:

您在这里执行两种不同的操作:

Period p = Period.between(d1, d2)

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

d1.until(d2, ChronoUnit.DAYS) 

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

【讨论】:

    【解决方案2】:

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

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

    计算从几年到几个月再到几天。这允许您计算 2014-02-142016-02-29 之间的年数、月数和天数,即 2 年零 15 天。

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

    【讨论】:

      【解决方案3】:

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

      2014 年 2 月 14 日2014 年 3 月 1 日之间的时间仅为 15 天

      2017 年 2 月 14 日2017 年 8 月 1 日 之间的 期间是从 2017 年 7 月 14 日 strong>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 给定的 @ 类987654321@ 执行您所需的日期计算。

      【讨论】:

        猜你喜欢
        • 2019-11-16
        • 1970-01-01
        • 2015-04-05
        • 1970-01-01
        • 2013-04-20
        • 2014-09-16
        • 2013-11-08
        • 2016-08-29
        • 2015-10-05
        相关资源
        最近更新 更多