Komal Komal - 1 year ago 42
Android Question

Calculate age from BirthDate

I have DatePicker Dialog, When I select date at that time I want to calculate age it's working but when I select date of current year at that time it showing the -1 age instead of 0 then how can solve this? Please help me to solve it.
My code is below:

public int getAge(int year, int month, int day) {

GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;

y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);// current day
cal.set(year, month, day);// here ur date
noofyears = (int) (y - cal.get(Calendar.YEAR));
LOGD("Age......", String.valueOf(noofyears));

if ((m < cal.get(Calendar.MONTH)) || ((m == cal.get(Calendar.MONTH)) && (d < cal.get(Calendar.DAY_OF_MONTH)))) {
LOGD("Age......", String.valueOf(noofyears));
if (noofyears != 0) {
ageCount = noofyears;
} else {
ageCount = 0;
if (noofyears < 0)
throw new IllegalArgumentException("age < 0");
return noofyears;

Answer Source

Here is a Java method called getAge which takes integers for year month and day and returns a String type which holds an integer that represents age in years.

private String getAge(int year, int month, int day){
    Calendar dob = Calendar.getInstance();
    Calendar today = Calendar.getInstance();

    dob.set(year, month, day); 

    int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

    if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){

    Integer ageInt = new Integer(age);
    String ageS = ageInt.toString();

    return ageS;