Java Age Calculate getAge(Date birthDate, Date controlDate)

Here you can find the source of getAge(Date birthDate, Date controlDate)

Description

age = the_year_of_controlDate - the_year_of_birthDate

License

LGPL

Parameter

Parameter Description
birthDate a parameter
controlDate a parameter

Declaration

public static Integer getAge(Date birthDate, Date controlDate) 

Method Source Code

//package com.java2s;
/*//  ww w. j  a  v  a 2  s .co  m
 * OpenClinica is distributed under the
 * GNU Lesser General Public License (GNU LGPL).
    
 * For details see: http://www.openclinica.org/license
 * copyright 2003-2007 Akaza Research
 */

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**
     * age = the_year_of_controlDate - the_year_of_birthDate
     * 
     * @param birthDate
     * @param controlDate
     * @return
     */
    public static Integer getAge(Date birthDate, Date controlDate) {
        Integer age = -1;
        if (birthDate.before(controlDate)) {
            Calendar dateOfBirth = Calendar.getInstance();
            dateOfBirth.setTime(birthDate);
            Calendar theDate = Calendar.getInstance();
            theDate.setTime(controlDate);
            age = theDate.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);
            Calendar today = Calendar.getInstance();
            // add the age to the year to see if it's happened yet
            dateOfBirth.add(Calendar.YEAR, age);
            // subtract one from the age if the birthday hasn't happened yet
            if (today.before(dateOfBirth)) {
                age--;
            }
        }
        return age;
    }
}

Related

  1. calculateAge(Date dateOfBirth)
  2. calculateAge(Date dob)
  3. calculateAge(Date DOB)
  4. calculateAgeInMonth(final Date birthDate, final Date asOfDate)
  5. calculateAgeInWeek(final Date birthDate, final Date asOfDate)
  6. getAge(Date birthDay)
  7. getAge(Date birthday)
  8. getAge(Date birthday)
  9. getAge(Date birthday)