How to Calculate Age From a Birthdate Using Java Date/Time?
Last Updated :
15 Feb, 2024
Calculate the age from a birthdate using the Data/Time API in Java programming, which was introduced in Java 8 to perform this calculation efficiently and accurately.
LocalDate
LocalDate is a pre-defined class of the Java Date/Time API. It depicts a date without a time zone and keeps the year, month, and day of the month.
Syntax:
LocalDate localDate = LocalDate.of(year, month, dayOfMonth);
Examples:
LocalDate januaryFirst2023 = LocalDate.of(2023, 1, 1); //it takes certain date
LocalDate currentDate = LocalDate.now(); //it takes the current date
Period
Period is a class of the Java Date/Time API which is used to depict a period in terms of years, months, and days and to describe the amount of time between two dates in terms of calendar.
Syntax:
Period periodBetween = Period.between(startDate, endDate);
It takes the starting date, ending date, and return year difference between the two dates.
Step-by-Step Implementation
- Create the Java class named GfgAgeCalculator and write the main method into the class.
- Import the related packages; in our case, import the LocalDate and Period packages for calculating the age using birthdate.
- Create the LocalDate instance named birthdate, and it can take the birthdate in the format of year, month, or day.
- Create one more LocalDate instance named currentDate, and it can take the currentDate.
- Now calculate the age between the birthdate and current date using the period.
- Print the result.
Sample Program:
Java
import java.time.LocalDate;
import java.time.Period;
public class GfGAgeCalculator {
public static void main(String[] args) {
LocalDate birthdate = LocalDate.of( 1997 , 10 , 03 );
LocalDate currentDate = LocalDate.now();
int age = calculateAge(birthdate, currentDate);
System.out.println( "Age: " + age + " years" );
}
public static int calculateAge(LocalDate birthdate, LocalDate currentDate) {
Period period = Period.between(birthdate, currentDate);
return period.getYears();
}
}
|
Share your thoughts in the comments
Please Login to comment...