Abhishek Singh Abhishek Singh -5 years ago 158
Java Question

Calculate months between two dates keeping year in mind using JodaTime

I am using this code to calculate no of months between input pastdate and currentdate. It uses JodaTime

LocalDate date1 = new LocalDate(installmentStartDate2);
LocalDate date2 = new LocalDate(new java.util.Date());
PeriodType monthDay = PeriodType.yearMonthDayTime();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
return months + 1;

Now when i enter 1 jan 2013 i get 10 as answer. But the problem is get 10 even when i enter 1 jan 2012.

So that means while calculation it doesn't considers year.

What can i do to get correct answer i.e., 22 when i enter 1 jan 2012.

Can JodaTime do that ? If yes ? How ?
If not ? Any other approach ?

Answer Source

Your code is almost correct.

You can change :

PeriodType monthDay = PeriodType.yearMonthDayTime();

to :

PeriodType monthDay = PeriodType.months();

and it will work also.

Greetz chill.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download