/**
* 根据生日计算年龄
* @param birthDay
* @return
*/
public static String getAgeByBirth(Date birthDay) {
StringBuffer sb = new StringBuffer();
try {
int age = 0;
int month = 0;
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);
age = yearNow - yearBirth; //计算整岁数
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
//if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前,年龄减一
} else {
month = monthNow - monthBirth + 12;
age--;//当前月份在生日之前,年龄减一
}
} else {
month = monthNow - monthBirth;
}
if (age < 4) {
if (age == 0) {
sb.append(month + "个月");
} else if (month == 0) {
sb.append(age + "岁");
} else {
sb.append(age + "岁" + month + "个月");
}
} else {
sb.append(age + "岁");
}
} catch (Exception e) {
return "";
}
return sb.toString();
}