VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-calculate-age-from-a-birthdate-using-java-date-time/

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


  • Courses
  • Tutorials
  • Interview Prep

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

  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:


Output
Age: 26 years

Comment