How to Calculate Age from Date of Birth in Java
The following Java program example calculates age of a person from his date of birth. This implementation is portable across Java versions. This implementation shows why date API in Java is bad before Java 8.
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Scanner; // Calculate age from date of birth in Java // Works in all Java versions public class CalculateAge { public static void main(String[] args) throws Exception { System.out.print("Please enter date of birth in YYYY-MM-DD: "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); scanner.close(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar dob = Calendar.getInstance(); dob.setTime(sdf.parse(input)); System.out.println("Age is:" + getAge(dob)); } // Returns age given the date of birth public static int getAge(Calendar dob) throws Exception { Calendar today = Calendar.getInstance(); int curYear = today.get(Calendar.YEAR); int dobYear = dob.get(Calendar.YEAR); int age = curYear - dobYear; // if dob is month or day is behind today's month or day // reduce age by 1 int curMonth = today.get(Calendar.MONTH); int dobMonth = dob.get(Calendar.MONTH); if (dobMonth > curMonth) { // this year can't be counted! age--; } else if (dobMonth == curMonth) { // same month? check for day int curDay = today.get(Calendar.DAY_OF_MONTH); int dobDay = dob.get(Calendar.DAY_OF_MONTH); if (dobDay > curDay) { // this year can't be counted! age--; } } return age; } }
In Java 8, A much more elegant implementation to calculate age can be written using classes in the new java.time package. Following example also demonstrates the use of LocalDate and Period classes in Java 8.
import java.time.LocalDate; import java.time.Period; import java.util.Scanner; // Java example program to calculate age from date of birth // Works only in Java 8 and above public class CalculateAgeJava8 { public static void main(String[] args) { System.out.print("Please enter date of birth in YYYY-MM-DD: "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); scanner.close(); LocalDate dob = LocalDate.parse(input); System.out.println("Age is:" + getAge(dob)); } // Returns age given the date of birth public static int getAge(LocalDate dob) { LocalDate curDate = LocalDate.now(); return Period.between(dob, curDate).getYears(); } }
The above implementation uses the default time zone for calculating current date. You may want to specify a time zone for precise age(!) calculation. LocalDate.now() is overloaded to specify time zone.
Another option is to use Joda Time library. However in Java 8 and beyond java.time implementation is the best solution. If you are migrating a Java project using Joda time to Java 8, it is now recommended to switch to java.time package.