Java 8计算两个日期之间的月份 [英] Java 8 calculate months between two dates
问题描述
请注意,这并非以下所有内容的重复
- Calculating the difference between two Java date instances
- calculate months between two dates in java [duplicate]
我有两个约会:
- 开始日期:
"2016-08-31"
- 结束日期:
"2016-11-30"
- Start date:
"2016-08-31"
- End date:
"2016-11-30"
在上述两个日期之间有91天的持续时间,我希望代码返回3个月的持续时间,但是以下方法仅返回2个月.有谁有更好的建议?还是你们认为这是Java 8中的错误? 91天的期限仅返回2个月.
Its 91 days duration between the above two dates, I expected my code to return 3 months duration, but the below methods only returned 2 months. Does anyone have a better suggestion? Or do you guys think this is a bug in Java 8? 91 days the duration only return 2 months.
非常感谢您的帮助.
方法1:
Period diff = Period.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30"));
方法2:
long daysBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30"));
方法3:
我尝试使用Joda库而不是Java 8 API,它可以工作.它会返回3,它看起来像Java持续时间月份的计算也使用了天数的值.但就我而言,我不能在项目中使用Joda.因此,仍在寻找其他解决方案.
I tried to use Joda library instead of Java 8 APIs, it works. it loos will return 3, It looks like Java duration months calculation also used days value. But in my case, i cannot use the Joda at my project. So still looking for other solutions.
LocalDate dateBefore= LocalDate.parse("2016-08-31");
LocalDate dateAfter = LocalDate.parse("2016-11-30");
int months = Months.monthsBetween(dateBefore, dateAfter).getMonths();
System.out.println(months);
推荐答案
由于您不在乎情况如何.您只需要两个日期之间的月份数,请使用期间的文档来调整日期,如Jacob
所述使用日期.只需将两个实例的日期设置为相同的值(每月的第一天)
Since you don't care about the days in your case. You only want the number of month between two dates, use the documentation of the period to adapt the dates, it used the days as explain by Jacob
. Simply set the days of both instance to the same value (the first day of the month)
Period diff = Period.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(diff); //P3M
与其他解决方案相同:
long monthsBetween = ChronoUnit.MONTHS.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(monthsBetween); //3
从 @OlivierGrégoire编辑评论:
Instead of using a LocalDate
and set the day to the first of the month, we can use YearMonth
that doesn't use the unit of days.
long monthsBetween = ChronoUnit.MONTHS.between(
YearMonth.from(LocalDate.parse("2016-08-31")),
YearMonth.from(LocalDate.parse("2016-11-30"))
)
System.out.println(monthsBetween); //3
这篇关于Java 8计算两个日期之间的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!