Calculate age from BirthDate
Here is a Kotlin extension of the Date
class returning the age corresponding to a Date
object
val Date.age: Int
get() {
val calendar = Calendar.getInstance()
calendar.time = Date(time - Date().time)
return 1970 - (calendar.get(Calendar.YEAR) + 1)
}
It 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.
private int getAge(String dobString){
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse(dobString);
} catch (ParseException e) {
e.printStackTrace();
}
if(date == null) return 0;
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.setTime(date);
int year = dob.get(Calendar.YEAR);
int month = dob.get(Calendar.MONTH);
int day = dob.get(Calendar.DAY_OF_MONTH);
dob.set(year, month+1, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
return age;
}
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)){
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
java.time
For the sake 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).