Java Program To Calculate Age From Year Of Birth
Chapter:
Miscellaneous
Last Updated:
16-09-2023 06:32:44 UTC
Program:
/* ............... START ............... */
import java.time.LocalDate;
import java.time.Period;
public class AgeCalculator {
public static void main(String[] args) {
// Assuming the person's birthdate is 1990-01-15
LocalDate birthdate = LocalDate.of(1990, 1, 15);
// Get the current date
LocalDate currentDate = LocalDate.now();
// Calculate the age
int age = Period.between(birthdate, currentDate).getYears();
System.out.println("The person's age is: " + age);
}
}
/* ............... END ............... */
Output
The person's age is: 33
This output indicates that the person's age is 33 years, based on the provided birthdate (1990-01-15)
and the current date when the program was executed.
Notes:
-
In this example, we use the java.time.LocalDate class to represent the birthdate and current date, and then we use the Period.between method to calculate the difference between the two dates in terms of years. Finally, we print out the person's age.
- Make sure you have Java 8 or a later version, as the java.time package was introduced in Java 8.