我有以下代码来计算 2 天之间的天数差异,01/09/2023 and 02/10/2023预期结果是 31 天,但代码返回 1 天。
LocalDate from = LocalDate.of(2023, 9, 1);
LocalDate to = LocalDate.of(2023, 10, 02);
Period period = Period.between(from, to);
System.out.print(period.getYears() + " years,");
System.out.print(period.getMonths() + " months,");
System.out.print(period.getDays() + " days");
Run Code Online (Sandbox Code Playgroud)
输出 :
0 years,1 months,1 days
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我的代码有什么问题
期间的各部分是相加的:两个日期之间的期间为 1 个月零1 天。
要计算 LocalDates 之间的天数,请使用until():
long daysBetween = from.until(to, ChronoUnit.DAYS);
Run Code Online (Sandbox Code Playgroud)
或方便的方法Between():
long daysBetween = ChronoUnit.DAYS.between(from, to);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |