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;
}
java.time
For the sage of completeness and being up-to-date concerning packages, here is the way using
java.time
(Java 8+).Java
Kotlin
Both snippets need the following imports from
java.time
:It's not recommended to use
java.util.Date
andjava.util.Calendar
anymore except from situations where you have to involve considerably large amounts of legacy code.See also Oracle Tutorial.
For projects supporting Java 6 or 7, this functionality is available via the ThreeTenBP,
while there is special version, the ThreeTenABP for API levels below 26 in Android.
Here is a Kotlin extension of the
Date
class returning the age corresponding to aDate
objectIt is compatible for all Android versions. If you wonder what '1970' is, that's the Unix Epoch. The timestamp is 0 on January 1, 1970.
after that create one class
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.