java 根据出生日期 获取年龄
时间: 2023-04-05 12:01:40 浏览: 116
Java根据生日计算年龄算法
您好,根据出生日期获取年龄的 Java 代码如下:
```java
public static int getAge(Date birthDate) {
Calendar cal = Calendar.getInstance();
if (cal.before(birthDate)) {
throw new IllegalArgumentException("出生日期在当前日期之后,无法计算年龄!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDate);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH) + 1;
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;
}
```
希望能对您有所帮助。
阅读全文