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.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 =;
        int age = Period.between(Dob,currentDate).getYears();
        return age;

Please enter your birth date (dd-mm-yyyy format) 

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 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:

One response to “How to calculate age from date of birth in Java”

  1. Lubangakene Gardson says:

    The program is fantastic. I tried modifying it to capture age as below

    package calculateAge;

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

    public class CalculateAge {

    public static void main(String[] args) {
    // TODO code application logic here

    Scanner input = new Scanner(;

    System.out.println(“Please Enter your name”);
    String name = input.nextLine();


    System.out.println(“Enter your DOB in yyyy-mm-dd format only”);
    String st = input.nextLine();

    LocalDate DOB;
    DOB = LocalDate.parse(st);

    LocalDate currentDate;
    currentDate =;

    int age = Period.between(DOB, currentDate).getYears();

    System.out.println(name+” You are “+age+” years old”);



Leave a Reply

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