Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate months between two dates keeping year in mind using JodaTime

Tags:

java

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 ?

like image 277
Abhishek Singh Avatar asked Oct 30 '13 08:10

Abhishek Singh


1 Answers

You're asking for the difference in years, months and days - so you're getting back 1 year, 10 months and 29 days.

Just use:

int months = Months.monthsBetween(date1, date2).getMonths();

Or if you really want to use new Period and perhaps get days as well you can use:

PeriodType monthDay = PeriodType.yearMonthDayTime().withYearsRemoved();
Period difference = new Period(date1, date2, monthDay);

You could just use PeriodType.months(), but if you're genuinely only interested in the months, I'd use the first snippet above to do it all in a single short-ish statement.

like image 83
Jon Skeet Avatar answered Oct 31 '22 23:10

Jon Skeet