gpt4 book ai didi

java - 两个 LocalDate 对象之间的周期计算似乎已关闭

转载 作者:行者123 更新时间:2023-11-30 01:46:42 25 4
gpt4 key购买 nike

我正在尝试计算两个 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

有人可以帮我弄清楚我是否遗漏了某些内容或预期结果有误(在我的代码和在线日期计算器中)?或者也许是我根本没有考虑到的其他事情。

以下是从在线日期计算器获得的结果的屏幕截图:

Result from online date calculator

最佳答案

您提供的在线日期计算器可能实现不正确。来 self 最喜欢的时间资源,timeanddate

From and including: Friday, May 19, 2017

To, but not including Saturday, July 13, 2019

Result: 785 days

It is 785 days from the start date to the end date, but not including the end date.

Or 2 years, 1 month, 24 days excluding the end date.

Or 25 month, 24 days excluding the end date.

这与 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();

关于java - 两个 LocalDate 对象之间的周期计算似乎已关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57681656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com