The age of the birthday calculation can be achieved by calendar. The simplest can be considered get (calendar.day_of_year) to simple correction of age, but encounter birthdays in leap years after February 29, or this is a leap year February 29 may appear after the calculation is not allowed, error one day. So it's good to be honest.
Based on the age of birthdays, judging the date, the calculation is more accurate than the simple year.
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) {
Monthnow==monthbirth
if (Dayofmonthnow < Dayofmonthbirth) {
age--;
} else {
Do nothing
}
} else {
Monthnow>monthbirth
age--;
}
} else {
Monthnow<monthbirth
Donothing
}
return age;
}
Java calculates age based on birthday