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;
}
根据生日计算年龄
最新推荐文章于 2021-02-25 09:43:00 发布