Java program to calculate age from year of birth
Chapter:
Miscellaneous
Last Updated:
29-06-2023 04:33:24 UTC
Program:
/* ............... START ............... */
import java.time.LocalDate;
import java.time.Period;
public class AgeCalculator {
public static int calculateAge(LocalDate birthDate) {
LocalDate currentDate = LocalDate.now();
return Period.between(birthDate, currentDate).getYears();
}
public static void main(String[] args) {
// Example usage
LocalDate birthDate = LocalDate.of(1990, 5, 15);
int age = calculateAge(birthDate);
System.out.println("Date of Birth: " + birthDate);
System.out.println("Current Date: " + LocalDate.now());
System.out.println("Age: " + age);
}
}
/* ............... END ............... */
Output
Date of Birth: 1990-05-15
Current Date: 2023-06-29
Age: 33
In this example, the birth date is set to May 15, 1990, and the current date is obtained
using LocalDate.now(). The calculated age, which is 33, is then printed to the console
along with the provided birth date and the current date.
Notes:
-
This code uses the java.time.LocalDate class introduced in Java 8, which represents a date without time information. The Period.between method is used to calculate the difference between the birthDate and the current date (LocalDate.now()), and the getYears method retrieves the number of years from the resulting Period object.
- In the main method, an example usage is provided where the calculateAge method is called with a specific birth date. The calculated age is then printed to the console.
- Note that you will need to have Java 8 or later to run this code due to the usage of the java.time package.
Tags
Java program to calculate age from year of birth #Write a Java method to calculate the age of a person given their date of birth #Java Calculate Age