Java Age Calculate getAge(Date dateNaissance)

Here you can find the source of getAge(Date dateNaissance)

Description

Retourne l'age en utilisant la date de naissance.

License

Open Source License

Parameter

Parameter Description
dateNaissance a parameter

Declaration

public static Integer getAge(Date dateNaissance) 

Method Source Code

//package com.java2s;
/*****************************************************************************
 * Copyright (c) 2009/*from  w  ww. ja v a2 s  . c om*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Angelo Zerr <angelo.zerr@gmail.com>
 *     Jawher Moussa <jawher.moussa@gmail.com>
 *     Nicolas Inchauspe <nicolas.inchauspe@gmail.com>
 *     Pascal Leclercq <pascal.leclercq@gmail.com>
 *******************************************************************************/

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

public class Main {
    /**
     * Retourne l'age en utilisant la date de naissance.
     * @param dateNaissance
     * @return
     */
    public static Integer getAge(Date dateNaissance) {
        Integer ageToReturn = null;
        if (dateNaissance != null) {
            // Create a calendar object with the date of birth
            Calendar dateOfBirth = Calendar.getInstance();
            dateOfBirth.setTime(dateNaissance);

            // Create a calendar object with today's date
            Calendar today = Calendar.getInstance();

            // Get age based on year
            int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);

            // Add the tentative age to the date of birth to get this year's birthday
            dateOfBirth.add(Calendar.YEAR, age);

            // If this year's birthday has not happened yet, subtract one from age
            if (today.before(dateOfBirth)) {
                age--;
            }
            ageToReturn = age;
        }
        return ageToReturn;
    }
}

Related

  1. getAge(Date birthday)
  2. getAge(Date birthday)
  3. getAge(Date birthday)
  4. getAge(Date date)
  5. getAge(Date date, TimeZone tz)
  6. getAge(Date time, Date birth)
  7. getAge(final Date birthDay, final Date currDate)
  8. getAge(String year)
  9. getAge1(Date birthDay)