I am writing a program that is supposed to just calculate the months between 2 given dates and return the value to the program. For instance, if I have to calculate the numb
Why do you expect the answer to be 3 months
? The precise answer is two months and a little bit, which then results in the two months you are getting.
If you want the number of months that are “touched” by this interval, this is a completely different question. Just add 1 to the result of the difference.
DateTime start = new DateTime().withDate(2011, 4, 1);
DateTime end = new DateTime().withDate(2011, 2, 1);
Period p = new Period(start, end, PeriodType.months().withDaysRemoved());
int months = p.getMonths();
System.out.println(months);
wrong output in this case
DateTime start = new DateTime().withDate(2011, 4, 1);
DateTime end = new DateTime().withDate(2011, 6, 30);
Period p = new Period(start, end, PeriodType.months().withDaysRemoved());
int months = p.getMonths() + 1;
You need the withDaysRemoved()
part to ensure that adding one to the number of months works. Otherwise two dates such as 2011-04-15
and 2011-06-14
would still result in the answer being 2
Let y1
and m1
be the year and month of the start date,
and y2
and m2
be the year and month of the end date.
Then the number of months between
start and end, including the months of the start and end dates is
(y2 - y1) * 12 + (m2 - m1) + 1
Joda algorithm counted correctly difference between this two dates. This pseudo-code will be the easiest way to explain how it works:
// (1)
monthsBetween(2011.6.14, 2011.4.15) = 1
monthsBetween(2011.6.15, 2011.4.15) = 2
// (2)
monthsBetween(2011.6.30, 2011.4.1) = 2
monthsBetween(2011.7.1, 2011.4.1) = 3
To do what you want you need to "improve" joda algorithm:
Months mt = Months.monthsBetween(
start.monthOfYear().roundFloorCopy(),
end.monthOfYear().roundCeilingCopy()
);