How do I calculate the number of years difference between 2 calendars in Java?
Enter the following formula in the formula bar =YEARFRAC (A2, B2) to calculate the years between the dates in cell A2 and cell B2.
First you need to determine which one is older than the other. Then make use of a while
loop wherein you test if the older one isn't after()
the newer one. Invoke Calendar#add()
with one (1
) Calendar.YEAR
on the older one to add the years. Keep a counter to count the years.
Kickoff example:
Calendar myBirthDate = Calendar.getInstance();
myBirthDate.clear();
myBirthDate.set(1978, 3 - 1, 26);
Calendar now = Calendar.getInstance();
Calendar clone = (Calendar) myBirthDate.clone(); // Otherwise changes are been reflected.
int years = -1;
while (!clone.after(now)) {
clone.add(Calendar.YEAR, 1);
years++;
}
System.out.println(years); // 32
That said, the Date
and Calendar
API's in Java SE are actually epic failures. There's a new Date API in planning for upcoming Java 8, the JSR-310 which is much similar to Joda-Time. As far now you may want to consider Joda-Time since it really eases Date/Time calculations/modifications like this. Here's an example using Joda-Time:
DateTime myBirthDate = new DateTime(1978, 3, 26, 0, 0, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);
int years = period.getYears();
System.out.println(years); // 32
Much more clear and concise, isn't it?
Calendar dobDate; // Set this to date to check
Calendar today = Calendar.getInstance();
int curYear = today.get(Calendar.YEAR);
int curMonth = today.get(Calendar.MONTH);
int curDay = today.get(Calendar.DAY_OF_MONTH);
int year = dobDate.get(Calendar.YEAR);
int month = dobDate.get(Calendar.MONTH);
int day = dobDate.get(Calendar.DAY_OF_MONTH);
int age = curYear - year;
if (curMonth < month || (month == curMonth && curDay < day)) {
age--;
}
This avoids looping and should be accurate to the day.
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