Friday, 20 January 2012

How to calculate an age in Java?

Can we calculate an age in java without worrying about number of leap years between birth date and current date? Is there simple way to calculate it? …. The answer is yes. When we calculate somebody’s age manually, we do not think about number of leap year or number of days in each year. Same logic can be applies for calculating age programmatically.

Following is a code snippet for calculating the age. Please leave comment if it has helped you. Also please let me know if you feel this can be further optimized or this can be achieved by more simpler way...

  int years = 0;
  int months = 0;
  int days = 0;
  //create calendar object for birth day
  Calendar birthDay = Calendar.getInstance();
  birthDay.set(Calendar.YEAR, 2005);
  birthDay.set(Calendar.MONTH, Calendar.SEPTEMBER);
  birthDay.set(Calendar.DATE, 29);
  //create calendar object for current day
  long currentTime = System.currentTimeMillis();
  Calendar currentDay = Calendar.getInstance();

  //Get difference between years
  years = currentDay.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);

  int currMonth = currentDay.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)
   months = 12 - birthMonth + currMonth;
  }else if(months == 0 && currentDay.get(Calendar.DATE) < birthDay.get(Calendar.DATE)){
   months = 11;
  //Calculate the days
   days = currentDay.get(Calendar.DATE) -  birthDay.get(Calendar.DATE);
  else if(currentDay.get(Calendar.DATE)<birthDay.get(Calendar.DATE)){
   int today = currentDay.get(Calendar.DAY_OF_MONTH); 
   currentDay.add(Calendar.MONTH, -1);
   days = currentDay.getActualMaximum(Calendar.DAY_OF_MONTH)-birthDay.get(Calendar.DAY_OF_MONTH)+today;
   if(months == 12){
    months = 0;
  System.out.println("The age is : "+years+" years, "+months+" months and "+days+" days" );


  1. I have checked it with many dates and it is correct on every occasion.Good work.

  2. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.

    java training in bangalore

  3. Hi,

    find Age Calculator then it is Overall looking for a Chronological age or anniversary calculator then this is your best option in age Calculator.

    Age Calculator By Date Of Birth (Days, Months)
    Calculation of age with interesting details!
    If you want to know the details of your age, then install the Age Calculator