java根据身份证算年龄
时间: 2023-06-26 08:04:03 浏览: 97
可以通过以下代码实现根据身份证号码计算年龄:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class AgeCalculator {
public static void main(String[] args) {
String idCard = "身份证号码";
int age = getAgeByIdCard(idCard);
System.out.println("年龄:" + age);
}
public static int getAgeByIdCard(String idCard) {
try {
String birthdayStr = idCard.substring(6, 14);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date birthday = format.parse(birthdayStr);
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) + 1;
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthday);
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 || (monthNow == monthBirth && dayOfMonthNow < dayOfMonthBirth)) {
age--;
}
return age;
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
```
将其中的“身份证号码”替换为实际的身份证号码即可得到该身份证号码对应的年龄。
阅读全文