public static int getAge(String idcard) throws Exception {
String strDate = "";
if(idcard.length() == 18){
strDate = idcard.substring(6,14);
}else if(idcard.length() == 15){
strDate = "19" + idcard.substring(6,12);
}else{
throw new RuntimeException("身份证号码格式错误");
}
System.out.println(strDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date birthDay = sdf.parse(strDate);
Calendar cal = Calendar.getInstance();
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
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) {
if (dayOfMonthNow < dayOfMonthBirth) age--;
}else{
age--;
}
}
return age;
}