java根据身份证计算年龄
时间: 2023-09-25 15:08:50 浏览: 89
可以通过以下代码来计算身份证对应的年龄:
```java
public static int calculateAge(String idCard) {
Calendar cal = Calendar.getInstance();
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
int yearBirth, monthBirth, dayOfMonthBirth;
if (idCard.length() == 18) {
yearBirth = Integer.parseInt(idCard.substring(6, 10));
monthBirth = Integer.parseInt(idCard.substring(10, 12));
dayOfMonthBirth = Integer.parseInt(idCard.substring(12, 14));
} else if (idCard.length() == 15) {
yearBirth = Integer.parseInt(idCard.substring(6, 8)) + 1900;
monthBirth = Integer.parseInt(idCard.substring(8, 10));
dayOfMonthBirth = Integer.parseInt(idCard.substring(10, 12));
} else {
return -1; // 身份证号码不合法
}
int age = yearNow - yearBirth;
if (monthNow < monthBirth || (monthNow == monthBirth && dayOfMonthNow < dayOfMonthBirth)) {
age--;
}
return age;
}
```
其中,idCard 为身份证号码,返回值为身份证对应的年龄。注意,这里假设传入的身份证号码是合法的,如果身份证号码不合法,返回值为 -1。
阅读全文