在网上找到了一个计算年龄的java程序代码,但是计算出来的年龄竟然会出现负数,跟踪后发现cal.get(Calendar.MONTH)获取到的月份是从0开始的,代码如下:
public static int getAge(Date birthDay) throws Exception {
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) {
throw new IllegalArgumentException(
"出生时间大于当前时间!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;//注意此处,如果不加1的话计算结果是错误的
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
//donothing
}
return age;
}