Use a org.joda.time.Period
:
// fields used by the period - use only months and days
PeriodType fields = PeriodType.forFields(new DurationFieldType[] {
DurationFieldType.months(), DurationFieldType.days()
});
Period period = new Period(dateOfBirth, endDate)
// normalize to months and days
.normalizedStandard(fields);
The normalization is needed because the period usually creates things like "1 month, 2 weeks and 3 days", and the normalization converts it to "1 month and 17 days". Using the specific DurationFieldType
's above also makes it convert years to months automatically.
Then you can get the number of months and days:
int months = period.getMonths();
int days = period.getDays();
Another detail is that when using DateTime
objects, the Period
will also consider the time (hour, minute, secs) to know if a day has passed.
If you want to ignore the time and consider only the date (day, month and year), don't forget to convert them to LocalDate
:
// convert DateTime to LocalDate, so time is ignored
Period period = new Period(dateOfBirth.toLocalDate(), endDate.toLocalDate())
// normalize to months and days
.normalizedStandard(fields);