Java根据身份证号计算年龄
Oxygen404:
public static Integer calculateAgeFromIdCard(String idCardNumber) {
String birthday = idCardNumber.substring(6, 14);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
Date birthDate = sdf.parse(birthday);
Calendar cal = Calendar.getInstance();
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH) + 1;
int currentDate = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDate);
int birthYear = cal.get(Calendar.YEAR);
int birthMonth = cal.get(Calendar.MONTH) + 1;
int birthDateOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int age = currentYear - birthYear;
if (currentMonth < birthMonth || (currentMonth == birthMonth && currentDate < birthDateOfMonth)) {
age--;
}
return age;
} catch (Exception e) {
e.printStackTrace();
}
// 解析出生日期失败或身份证号码无效
return -1;
}
|