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
For the sage of completeness and being up-to-date concerning packages, here is the way using java.time
(Java 8+).
Java
public int getAge(int year, int month, int dayOfMonth) {
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).getYears();
}
Kotlin
fun getAge(year: Int, month: Int, dayOfMonth: Int): Int {
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).years
}
Both snippets need the following imports from java.time
:
import java.time.LocalDate;
import java.time.Period
It's not recommended to use java.util.Date
and java.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.
UPDATE
There's API Desugaring now in Android, which makes (a subset of) java.time
directly available (no backport library needed anymore) to API levels below 26 (not really down to version 1, but will do for most of the API levels that should be supported nowadays).