Java Day of getAge(Date birthDay)

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

Description

get Age

License

Open Source License

Declaration

public static int getAge(Date birthDay) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.text.DateFormat;

import java.text.SimpleDateFormat;

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

public class Main {

    public static int getAge(String strBirthDay, String format) throws Exception {
        DateFormat df = new SimpleDateFormat(format);
        Date birthDay = df.parse(strBirthDay);
        return getAge(birthDay);
    }// w w w  .  j  a v  a 2s .  com

    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }
}

Related

  1. formatDayTime(String day)
  2. formatShortNameOfDay(final Date date)
  3. get1DayBeforDate()
  4. get8BitTime(Date date, int deltaDay)
  5. getAfterDays(String date, String pattern, int afterDays)
  6. getAgeOfCalendar(String birthDayString)
  7. getApisPaxBirthday(String dob)
  8. getBeforeDate(int day)
  9. getBeforeOrAfterDay(Date date, String format, Integer days)