Java Age Calculate getAge(Date date)

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

Description

get Age

License

Apache License

Declaration

public static int getAge(Date date) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static int getAge(Date date) {
        Calendar now = Calendar.getInstance();
        Calendar dob = Calendar.getInstance();
        dob.setTime(date);// ww  w  . j a  v a 2s  . co m
        if (dob.after(now)) {
            throw new IllegalArgumentException("Can't be born in the future");
        }
        int year1 = now.get(Calendar.YEAR);
        int year2 = dob.get(Calendar.YEAR);
        int age = year1 - year2;
        int month1 = now.get(Calendar.MONTH);
        int month2 = dob.get(Calendar.MONTH);
        if (month2 > month1) {
            age--;
        } else if (month1 == month2) {
            int day1 = now.get(Calendar.DAY_OF_MONTH);
            int day2 = dob.get(Calendar.DAY_OF_MONTH);
            if (day2 > day1) {
                age--;
            }
        }
        return age;
    }
}

Related

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