You can use Joda Time and calculate Period between the two LocalDate values ββ(which you got here), using months and years as units.
Code example:
import org.joda.time.*; public class Test { public static void main(String[] args) { LocalDate dob = new LocalDate(1992, 12, 30); LocalDate date = new LocalDate(2010, 12, 29); Period period = new Period(dob, date, PeriodType.yearMonthDay()); System.out.println(period.getYears() + " years and " + period.getMonths() + " months"); } }
(This uses a period type that also includes days, but this will not affect the response.)
All in all, Joda Time is a much better API than using Date / Calendar - and you really don't want you to do the date calculations yourself if you can avoid it. It gets very dirty.
According to the answer in aioobe, if you separate the two integer expressions, the arithmetic will be done in integer arithmetic, which may not be what you want, but for date and time arithmetic, just let someone else do the hard work first: )
The code above will use the ISO-8601 calendar, which is basically a Gregorian calendar. If you want to use something else, specify it as another constructor argument after the year / month / day for LocalDate .
source share