Abhishek Singh
Abhishek Singh

Reputation: 9765

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 ?

Upvotes: 6

Views: 13058

Answers (4)

android developer
android developer

Reputation: 116060

I suggest using this:

ChronoUnit.MONTHS.between(earlierDate,date)

Upvotes: 0

Gabber
Gabber

Reputation: 7249

Joda time is good way to dealing with this problem

Create a joda time date object

DateTime startDate = DateTime.parse("1970-01-01", DateTimeFormat.forPattern("yyyy-MM-dd"))
DateTime endDate = DateTime.parse("2015-02-25", DateTimeFormat.forPattern("yyyy-MM-dd"))

Difference between two dates in days

int days = Days.daysBetween(startDate, endDate).getDays()

Difference between two dates in months

int months = Months.monthsBetween(startDate.withDayOfMonth(1), endDate.withDayOfMonth(1)).getMonths()

Difference between two dates in years

int years = Years.yearsBetween(startDate, endDate).getYears();

Upvotes: 1

chillworld
chillworld

Reputation: 4279

Your code is almost correct.

You can change :

PeriodType monthDay = PeriodType.yearMonthDayTime();

to :

PeriodType monthDay = PeriodType.months();

and it will work also.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503799

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.

Upvotes: 20

Related Questions