Java – joda time – month difference between two dates

See the English answer > number of days between two dates in joda time

DateTime date1 = new DateTime().withDate(2015,2,1);
DateTime date2 = new DateTime().withDate(2015,1,1);
Months m = Months.monthsBetween(date1,date2);
int monthDif = m.getMonths();//this return 0

It returns 0 because there is no month between the two dates. I need to return the difference within a few months instead of between months, and there will be a problem adding 1 when the dates are the same

Solution

Change the first date to February 2, 2015, and joda returns 1 month correctly:

DateTime date1 = new DateTime().withDate(2015,2);
DateTime date2 = new DateTime().withDate(2015,1);

System.out.println(Months.monthsBetween(date2,date1).getMonths());
// Returns 1.

So my guess is that you didn't provide the time part, and joda can't accurately determine the exact location pointed to by 2015-01-01 date 2 You may have mentioned 23:59:59. In this case, technically, a whole month has not passed

If you explicitly provide a zero time component, it will work as you originally expected:

DateTime date1 = new DateTime().withDate(2015,1).withTime(0,0);
DateTime date2 = new DateTime().withDate(2015,0);

System.out.println(Months.monthsBetween(date2,date1).getMonths());
// Returns 1.

Therefore, I suggest you specify the 00:00:00 time part of each date

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>