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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With