Java – Calculate Age from Date of Birth

To calculate age from date of birth for any person seems a really simple thing to do and it is indeed. In a very broad sense, I can visualize three solutions for this age calculator program.

1. Java 8 Period class

In Java 8, Period class is used to define an amount of elapsed time with date-based values (years, months, days).

Given below is a Java 8 program to calculate the age of a person from the date of birth. The program uses Period class to store the differences between two LocalDate instances. We are using Period to store the difference between today’s date and the person’s date of birth.

Once the Period is obtained, we can get the difference between both dates in desired metrics.

Note that birthday is inclusive, while today date is exclusive in the calculated period.

LocalDate today = LocalDate.now(); // Today's date is 10th Jan 2022
LocalDate birthday = LocalDate.of(1980, Month.JANUARY, 1); // Birth date

Period p = Period.between(birthday, today);

// Now access the values as below
System.out.println(p.getDays());    //9
System.out.println(p.getMonths());  //0
System.out.println(p.getYears());   //42

2. Jodatime Library

We know that the new Java 8 date time API is inspired by the Joda library. Joda also has Period class that is very much similar to Java 8 Period class.

So this solution is also very similar to Java 8 solution.

LocalDate birthdate = new LocalDate (1970, 1, 20); 		//Birth date
LocalDate now = new LocalDate();						//Today's date

Period period = new Period(birthdate, now, PeriodType.yearMonthDay());

//Now access the values as below
System.out.println(period.getDays());
System.out.println(period.getMonths());
System.out.println(period.getYears());

The only difference between the above two examples is method between() which is not available in Period class in Joda library, rather dates are passed to the constructor.

3. Calculate Age using Date and Calendar

This solution is very basic and should be used for only learning the logic of calculation. I will not recommend this method for production-class applications. Though it works fine but code is not very readable. The low performance (not measured accurately) can be also a downside.

I have made some effort by adding Age class to make this solution look professional. 😉

I have made the default constructor private and provided a constructor which accepts days, months, years. We can add parameter validation as well so that it does not accept negative values.

public class Age
{
   private int days;
   private int months;
   private int years;

   private Age()
   {
      //Prevent default constructor
   }

   public Age(int days, int months, int years)
   {
      this.days = days;
      this.months = months;
      this.years = years;
   }

   public int getDays()
   {
      return this.days;
   }

   public int getMonths()
   {
      return this.months;
   }

   public int getYears()
   {
      return this.years;
   }

   @Override
   public String toString()
   {
      return years + " Years, " + months + " Months, " + days + " Days";
   }
}

Second class is AgeCalculator itself which has a private method which accept a person’s date of birth and return the Age instance having person’s age information.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AgeCalculator
{
   private static Age calculateAge(Date birthDate)
   {
      int years = 0;
      int months = 0;
      int days = 0;

      //create calendar object for birth day
      Calendar birthDay = Calendar.getInstance();
      birthDay.setTimeInMillis(birthDate.getTime());

      //create calendar object for current day
      long currentTime = System.currentTimeMillis();
      Calendar now = Calendar.getInstance();
      now.setTimeInMillis(currentTime);

      //Get difference between years
      years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
      int currMonth = now.get(Calendar.MONTH) + 1;
      int birthMonth = birthDay.get(Calendar.MONTH) + 1;

      //Get difference between months
      months = currMonth - birthMonth;

      //if month difference is in negative then reduce years by one
      //and calculate the number of months.
      if (months < 0)
      {
         years--;
         months = 12 - birthMonth + currMonth;
         if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
            months--;
      } else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
      {
         years--;
         months = 11;
      }

      //Calculate the days
      if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
         days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
      else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
      {
         int today = now.get(Calendar.DAY_OF_MONTH);
         now.add(Calendar.MONTH, -1);
         days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
      }
      else
      {
         days = 0;
         if (months == 12)
         {
            years++;
            months = 0;
         }
      }
      //Create new Age object
      return new Age(days, months, years);
   }

   public static void main(String[] args) throws ParseException
   {
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
      Date birthDate = sdf.parse("29/11/1981");
      Age age = calculateAge(birthDate);
      System.out.println(age);
   }
}

Program Output.

32 Years, 5 Months, 27 Days

In above examples, we learned to write a program to calculate the age of a person in java. Let me know your thoughts on the above solutions.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

13 thoughts on “Java – Calculate Age from Date of Birth”

  1. import java.util.Scanner;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.text.ParseException;

    public class EmployeeDetails{
    public static void main(String str[]) throws Exception{
    Scanner sc = new Scanner(System.in);
    System.out.print(“Enter name : “);
    String name =sc.nextLine();
    System.out.print(“Enter password :”);
    String pass =sc.nextLine();
    System.out.print(“DOB(dd/MM/yyyy) :”);
    String dop =sc.nextLine();
    try{
    SimpleDateFormat sdf = new SimpleDateFormat(“dd/MM/yyyy”);
    Date birthDate =sdf.parse(dop);
    Age age = calculateAge(birthDate);

    System.out.print(“Enter Designation No(0 to 2):”);
    int desino =sc.nextInt();
    System.out.print(“Enter Sub_Designation No(0 to 2):”);
    int sub_desino =sc.nextInt();
    System.out.print(“Enter Year of Join :”);
    int yoj =sc.nextInt();
    int cy =Calendar.getInstance().get(Calendar.YEAR);

    String desig[] =new String[3];
    desig[0] =”Admin”;
    desig[1] =”Manager”;
    desig[2] =”HR”;
    String sub_desig[] =new String[3];
    sub_desig[0] =”Level 1″;
    sub_desig[1] =”Level 2″;
    sub_desig[2] =”Level 3″;

    int yearDif= cy-yoj;
    double basic_Pay =(yearDif<4)? 10000:(yearDif3)? 20000:30000;

    double Dearness_Allowance =(20*basic_Pay)/100;
    double HRA =(7*basic_Pay)/100;
    double tax =(basic_Pay*2)/100;

    double gross_Pay = Dearness_Allowance+HRA+tax;
    double net_Pay =gross_Pay-(HRA+tax);

    System.out.println(“\t EmployeeName :”+name);
    System.out.println(“\t EmployeePassword :”+pass);
    System.out.println(“\t EmployeeDOB :”+dop);
    System.out.println(“\t EmployeeAge :”+age);

    System.out.println(“\t\tDesignation :”+desig[desino]);
    System.out.println(“\t\tSub_Designation :”+sub_desig[sub_desino]);
    System.out.println(“\t\tYear of Experiance :”+yearDif);
    System.out.println(“\t\tBasic Pay :”+basic_Pay+” $”);
    System.out.println(“\t\tGross Salary :”+gross_Pay+” $”);
    System.out.println(“\t\tNet Salary :”+net_Pay+” $”);

    }catch(ParseException e){

    }

    }
    private static Age calculateAge(Date birthDate){
    int years =0;
    int months =0;
    int days =0;

    Calendar birthday =Calendar.getInstance();
    birthday.setTimeInMillis(birthDate.getTime());

    long currentTime = System.currentTimeMillis();
    Calendar now = Calendar.getInstance();
    now.setTimeInMillis(currentTime);

    years = now.get(Calendar.YEAR) – birthday.get(Calendar.YEAR);
    int currMonth = now.get(Calendar.MONTH) + 1;
    int birthMonth = birthday.get(Calendar.MONTH) + 1;

    months = currMonth – birthMonth;

    if (months < 0)
    {
    years–;
    months = 12 – birthMonth + currMonth;
    if (now.get(Calendar.DATE) < birthday.get(Calendar.DATE))
    months–;
    } else if (months == 0 && now.get(Calendar.DATE) birthday.get(Calendar.DATE))
    days = now.get(Calendar.DATE) – birthday.get(Calendar.DATE);
    else if (now.get(Calendar.DATE) < birthday.get(Calendar.DATE))
    {
    int today = now.get(Calendar.DAY_OF_MONTH);
    now.add(Calendar.MONTH, -1);
    days = now.getActualMaximum(Calendar.DAY_OF_MONTH) – birthday.get(Calendar.DAY_OF_MONTH) + today;
    }
    else
    {
    days = 0;
    if (months == 12)
    {
    years++;
    months = 0;
    }
    }
    //Create new Age object
    return new Age(days, months, years);
    }
    }

    class Age
    {
    private int days;
    private int months;
    private int years;

    private Age()
    {
    //Prevent default constructor
    }

    public Age(int days, int months, int years)
    {
    this.days = days;
    this.months = months;
    this.years = years;
    }

    public int getDays()
    {
    return this.days;
    }

    public int getMonths()
    {
    return this.months;
    }

    public int getYears()
    {
    return this.years;
    }

    @Override
    public String toString()
    {
    return years + " Years, " + months + " Months, " + days + " Days";
    }
    }

    Reply
    • Thank for this code Lokesh.It’s save me.
      I’m fixed this issue.

      if (months < 0) {
      years–;
      months = 12 – birthMonth + currMonth;
      if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
      months–;
      //} else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
      } else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
      if (months == 0) {
      years–;
      months = 11;
      } else {
      months–;
      }
      }

      Hope it is useful for those who have seen it like me.

      Reply
  2. import java.util.*;
    import javax.swing.*;
    public class BirthDate
    {
    public static void main(String args[])
    {
    Scanner sn=new Scanner(System.in);
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    Calendar today=Calendar.getInstance();
    int dd,mm,yy;
    dd=today.get(Calendar.DATE);
    mm=today.get(Calendar.MONTH)+1;
    yy=today.get(Calendar.YEAR);
    cal1.set(yy, mm, dd); //set current date
    System.out.print(“Enter your date of birth(dd mm year): “);
    dd=Integer.parseInt(JOptionPane.showInputDialog(“DD: “));
    mm=Integer.parseInt(JOptionPane.showInputDialog(“MM: “));
    yy=Integer.parseInt(JOptionPane.showInputDialog(“YY: “));

    cal2.set(yy, mm, dd); // set date of birth
    int days=daysBetween(cal1.getTime(),cal2.getTime()); //number of days
    System.out.println(“Days= “+days);
    int year=days/365; // findout year
    days=days%365;
    int month=days/30; //findout month
    days=days%30;
    System.out.println(“YOUR age is “+year+” yrea “+month+” month “+days+” days”);
    }
    public static int daysBetween(Date d1, Date d2)
    {
    return (int)( (d1.getTime() – d2.getTime()) / (1000 * 60 * 60 * 24));
    }
    }

    Reply
  3. // date format: yyyy-MM-dd
    private int getAge(String birthdate, String today){
    String birth[] = birthdate.split(“-“);
    String now[] = today.split(“-“);
    int age = 0;

    int ybirth = Integer.parseInt(birth[0]);
    int mbirth = Integer.parseInt(birth[1]);
    int dbirth = Integer.parseInt(birth[2]);

    int ynow = Integer.parseInt(now[0]);
    int mnow = Integer.parseInt(now[1]);
    int dnow = Integer.parseInt(now[2]);

    if(ybirth dnow)
    age–;
    }else if(mbirth > mnow){ age–; }
    }

    return age;
    }

    Reply
  4. Period p = Period.between(birthday, today);
     
    //Now access the values as below
    System.out.println(period.getDays());
    System.out.println(period.getMonths());
    System.out.println(period.getYears());

    It should be:

    System.out.println(p.getDays());
    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.