Java Calculate Age from Date of Birth
In this Java tutorial, we learn how to calculate age of someone from with their birthday as a Date object in Java programming language.
How to calculate age from Date of birth in Java
In this first step, we create a new Java class named DateUtil, and implement the getAge(Date birthday) static method, this method to calculate the number of age based on a given Date object and current system Date as Java code below.
DateUtil.java
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
/**
* This method to calculate number of age from given birthday Date value.
* @param birthday the Date of birth
* @return number of age
*/
public static int getAge(Date birthday) {
Calendar birthdayCalendar = Calendar.getInstance();
birthdayCalendar.setTime(birthday);
Calendar todayCalendar = Calendar.getInstance();
int age = todayCalendar.get(Calendar.YEAR) - birthdayCalendar.get(Calendar.YEAR);
return age;
}
}
In the following example Java code, we learn how to use the above getAge(Date birthday) static method to calculate age from given Date object in Java program.
GetAgeFromDateExample.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GetAgeFromDateExample {
public static void main(String... args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date birthDate = simpleDateFormat.parse("1988/07/11");
// Calculate Age from Date of Birth
int age = DateUtil.getAge(birthDate);
System.out.println("Today: " + new Date());
System.out.println("Date of birth: " + birthDate);
System.out.println("Age: " + age);
}
}
Today: Thu Aug 18 22:51:21 ICT 2022
Date of birth: Mon Jul 11 00:00:00 ICT 1988
Age: 34
Happy Coding 😊
Related Articles
Java Calculate Age from Calendar of Birth
Java Calculate Age from Instant of Birth
Java Calculate Age from LocalDate of Birth
Java Calculate Age from LocalDateTime of Birth