英文:
How to get number of months between dates?
问题
now
和 now + 2 个月
之间的差异在这个示例中不等于2,尽管我认为LocalDate
的数学运算应该是这样的:
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.MONTHS;
public class MyClass {
public static void main(String... args) {
LocalDate now = LocalDate.of(2020, 7, 31);
LocalDate later = now.plusMonths(2);
System.out.println("Now: " + now);
System.out.println("Later: " + later);
System.out.println("Months between now and later: " + MONTHS.between(now, later));
}
}
输出结果为:
Now: 2020-07-31
Later: 2020-09-30
Months between now and later: 1
我之所以发现这一点,是因为我碰巧运行了一个单元测试,该测试落在一个打破预期的日期上...
查看LocalDate.plusMonths
的javadoc:
此方法将指定的月数添加到月份字段,分为三个步骤:
- 将输入的月份添加到年份的月份字段。
- 检查生成的日期是否无效。
- 必要时调整日期的日字段为最后一个有效日期。
例如,2007-03-31 加一月会导致无效日期 2007-04-31。而不是返回无效结果,选择了该月的最后一个有效日期 2007-04-30。
这意味着这是按照预期工作的。所以,不需要使用老式的 Date/Time API...
获取两个日期之间的月份数的正确方法是什么?
英文:
The difference between now
and now + 2 months
not equal to 2 in this example, despite my thinking LocalDate
math worked this way:
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.MONTHS;
public class MyClass {
public static void main(String... args) {
LocalDate now = LocalDate.of(2020, 7, 31);
LocalDate later = now.plusMonths(2);
System.out.println("Now: " + now);
System.out.println("Later: " + later);
System.out.println("Months between now and later: " + MONTHS.between(now, later));
}
}
Outputs:
Now: 2020-07-31
Later: 2020-09-30
Months between now and later: 1
I found this out only because I happened to run a unit test that fell on a date that breaks the expectation...
Reviewing the javadoc for LocalDate.addMonths:
> This method adds the specified amount to the months field in three
> steps:
>
> Add the input months to the month-of-year field
> Check if the resulting date would be invalid
> Adjust the day-of-month to the last valid day if necessary
>
> For example, 2007-03-31 plus one month would result in the invalid
> date 2007-04-31. Instead of returning an invalid result, the last
> valid day of the month, 2007-04-30, is selected instead.
Meaning this is working as intended. So without resorting to the vintage Date/Time api...
What is the correct way to get the number of months between two dates?
答案1
得分: 5
你可以使用YearMonth
类来仅考虑年份和月份。 <sup>示例</sup>
System.out.println(
"现在和稍后之间的月份差:" +
ChronoUnit.MONTHS.between(
YearMonth.from(now),
YearMonth.from(later)
)
);
导入java.time.temporal.ChronoUnit
和java.time.YearMonth
。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论