java 计算月份,Java 8计算两个日期之间的月份

NOTE THIS IS NOT A DUPLICATE OF EITHER OF THE FOLLOWING

I have two dates:

Start date: "2016-08-31"

End date: "2016-11-30"

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.

Thank you very much for the help.

Method 1:

Period diff = Period.between(LocalDate.parse("2016-08-31"),

LocalDate.parse("2016-11-30"));

Method 2:

long daysBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2016-08-31"),

LocalDate.parse("2016-11-30"));

Method 3:

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);

解决方案

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

Same with the other solution :

long monthsBetween = ChronoUnit.MONTHS.between(

LocalDate.parse("2016-08-31").withDayOfMonth(1),

LocalDate.parse("2016-11-30").withDayOfMonth(1));

System.out.println(monthsBetween); //3

Edit from @Olivier Grégoire comment:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值