pondělí 8. prosince 2008

How to calculate age?

I offten have on my projects a lot of conditions, which depends on the age of the client, user, his wife or dog ;-).

Standard Java API is not very friendly for this use case. If you can't use JodaTime as me, I hope you appreciate this little calculator.



public class AgeCalculator {

public static int getAge(final Date dayOfBirth) {
return getAge(dayOfBirth, new Date());
}

public static int getAge(final Date dayOfBirth, final Date referenceDay) {
if (dayOfBirth == null) {
throw new IllegalArgumentException("Parameter 'dayOfBirth' can't be null.");
}
if (referenceDay == null) {
throw new IllegalArgumentException("Parameter 'referenceDay' can't be null.");
}

final Calendar calRef = Calendar.getInstance();
calRef.setTime(referenceDay);

final Calendar cal = Calendar.getInstance();
cal.setTime(dayOfBirth);

final int yearRef = calRef.get(Calendar.YEAR);

final int year = cal.get(Calendar.YEAR);

int result = yearRef - year;

cal.set(Calendar.YEAR, yearRef);
if (calRef.before(cal)) {
result--;
}

return result;
}

}

Žádné komentáře: