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)))) {
--noofyears;
}
LOGD("Age......", String.valueOf(noofyears));
if (noofyears != 0) {
ageCount = noofyears;
} else {
ageCount = 0;
}
if (noofyears < 0)
throw new IllegalArgumentException("age < 0");
return noofyears;
}
This is how I implement in my source code, I tested. Hope that it is useful :
Now for kotlin Language: