【问题标题】:Calculation of Period between two LocalDate objects seems to be off两个 LocalDate 对象之间的周期计算似乎已关闭
【发布时间】:2019-08-27 20:12:27
【问题描述】:

我正在尝试计算两个 LocalDate 对象之间的差异,结果似乎是关闭的,但不是每次。

我正在使用 Period 构造。下面的代码显示了一个返回预期结果的示例(我得到了here)和另一个给我“错误”结果的示例。我把它放在引号中是因为我不确定这是否真的是错误的,或者预期值是否错误。但是请注意,如果我使用来自calculator.net 的在线计算器,我会得到我期望的结果。

      public void manualTestPeriodBetween() {
        //works fine - expected result obtained
        LocalDate start = LocalDate.of(2014, 2, 14);
        LocalDate end = LocalDate.of(2017, 8, 1);
        Period result = Period.between(start, end);
        Period expected = Period.of(3, 5, 18);
        checkPeriods(expected, result);

        //does not work as expected
        start = LocalDate.of(2017, 5, 19);
        end = LocalDate.of(2019, 7, 13);
        result = Period.between(start, end);
        expected = Period.of(2, 1, 25);
        checkPeriods(expected, result);
      }
      private void checkPeriods(Period expected, Period result) {
        System.out.println("expected Period = " + expected + ", resulting Period = " + result);
        if (result.equals(expected)) {
          System.out.println("SUCCESS - result Period matches expected");
        } else {
          System.out.println("FAIL - result Period not matched");
        }
      }

输出:

expected Period = P3Y5M18D, resulting Period = P3Y5M18D
SUCCESS - result Period matches expected
expected Period = P2Y1M25D, resulting Period = P2Y1M24D
FAIL - result Period not matched

谁能帮我弄清楚我是否遗漏了什么或预期的结果是错误的(在我的代码和在线日期计算器中)?或者我什至没有考虑其他的事情。

这是从在线日期计算器获得的结果截图:

【问题讨论】:

    标签: java


    【解决方案1】:

    您提供的在线日期计算器可能使用不正确。来自我最喜欢的时间资源,timeanddate

    从(含)开始:2017 年 5 月 19 日,星期五

    至,但不包括 2019 年 7 月 13 日星期六

    结果:785 天

    从开始日期到结束日期是 785 天,但不包括结束日期。

    或 2 年 1 个月 24 天(不包括结束日期)。

    或 25 个月 24 天,不包括结束日期。

    这与thecalculatorsite.com提供的响应相同

    我没有您的在线计算器的实现,但似乎存在差异,因为 5 月是 31 天的月份。

    它看起来是在计算月差之前的日差,使用一些数学假设来计算月份长度。

    Java 方法使用epochday 计算两天之间的距离以防下溢,而不是添加任意值来偏移一个月。

        if (totalMonths > 0 && days < 0) {
            totalMonths--;
            LocalDate calcDate = this.plusMonths(totalMonths);
            days = (int) (end.toEpochDay() - calcDate.toEpochDay());  // safe
        } else if (totalMonths < 0 && days > 0) {
            totalMonths++;
            days -= end.lengthOfMonth();
    

    【讨论】:

      【解决方案2】:

      我的意思是,应该是 24 天,具体取决于您的计算方式。

      如果您添加一个月到 6 月 19 日,而 6 月有 30 天,那么这两个日期之间只有 24 天。

      https://www.wolframalpha.com/input/?i=days+between+5%2F19%2F2017+and+7%2F13%2F2019

      您正在检查的网站是错误的,我可以想到几种可能发生的方式,具体取决于他们如何实现日期差异功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-17
        • 2022-12-06
        • 2017-07-30
        • 1970-01-01
        • 2018-08-09
        • 1970-01-01
        • 1970-01-01
        • 2021-10-16
        相关资源
        最近更新 更多