Open In App

How to Calculate Age From a Birthdate Using Java Date/Time?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  1. Create the Java class named GfgAgeCalculator and write the main method into the class.
  2. Import the related packages; in our case, import the LocalDate and Period packages for calculating the age using birthdate.
  3. Create the LocalDate instance named birthdate, and it can take the birthdate in the format of year, month, or day.
  4. Create one more LocalDate instance named currentDate, and it can take the currentDate.
  5. Now calculate the age between the birthdate and current date using the period.
  6. Print the result.

Sample Program:

Java




import java.time.LocalDate;
import java.time.Period;
  
// Driver Class
public class GfGAgeCalculator {
    // Main Function
    public static void main(String[] args) {
        // Birthdate
        LocalDate birthdate = LocalDate.of(1997, 10, 03);
  
        // Current Date
        LocalDate currentDate = LocalDate.now();
  
        // Calculate Age
        int age = calculateAge(birthdate, currentDate);
  
        // Print Age
        System.out.println("Age: " + age + " years");
    }
  
    public static int calculateAge(LocalDate birthdate, LocalDate currentDate) {
        // Calculate period between birthdate and current date
        Period period = Period.between(birthdate, currentDate);
          
          return period.getYears();
    }
}


Output

Age: 26 years


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads