How to calculate age from date of birth in Java

Hey Everyone! In this tutorial, we will learn how to calculate age from Date of Birth in Java provided by the user as input.


For this tutorial please consider using Java version 8 and above.

New Date and Time API was introduced in Java 8.
For calculating the age from Date of birth we will be using the LocalDate class which is present in java.time.LocalDate package.
Let’s take a look at the program.

Java Program to Calculate Age from  Date of birth

package birthdate;

import java.time.*;
import java.util.Scanner;


public class BirthDate {

    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your birth date (yyyy-mm-dd format only) ");
        String st = sc.nextLine();
        
        LocalDate Dob;
        Dob = LocalDate.parse(st);    
        
        System.out.println("Age is :- "+calcAge(Dob));
    }
    
    static int calcAge(LocalDate Dob)
    {
        LocalDate currentDate = LocalDate.now();
        int age = Period.between(Dob,currentDate).getYears();
        return age;
    }
}
Input:-

Please enter your birth date (dd-mm-yyyy format) 
1999-04-20
Output:-

Age is :- 20

In the above program, the user is prompted for input as the date of birth.
Then the date of birth string is passed as a parameter to the parse method of LocalDate class which in turn returns a reference to the Dob object.
This object is passed as a parameter to the method calcAge().
In this method the LocalDate.now() returns the current time in days,months,years.
Using the between.getyears() method two parameters are passed one is the current date and the other one is the date of birth.
This method returns the difference in years between the two dates thus giving us the age of the user calculated from the date of birth.


I hope this article was helpful to you. If you have any doubts or suggestions please leave a comment down below.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *