/**
* @author
* @Description 根据身份证号码计算年龄工具类 不考虑身份证有效问题
*/
public class IdCardUtils {
/**
* 根据身份证号码计算年龄
* @param idCard
* @return
*/
public static Object getAgeFromIdCard(String idCard){
Integer age;
String age1;
if (!StringUtils.isEmpty(idCard)) {
//截取身份证中年、月、日
Integer year = Integer.parseInt(idCard.substring(6, 10));
Integer month = Integer.parseInt(idCard.substring(10, 12));
Integer day = Integer.parseInt(idCard.substring(12, 14));
//得到当前年月日
Calendar calendar = Calendar.getInstance();
Integer yearNow = calendar.get(Calendar.YEAR);
Integer monthNow = calendar.get(Calendar.MONTH) + 1;
Integer dayNow = calendar.get(Calendar.DATE);
//当前时间减去生日时间
Integer yearMinus = yearNow - year;
Integer monthMinus = monthNow - month;
Integer dayMinus = dayNow - day;
//先大体赋值一下
age = yearMinus;
if (yearMinus == 0) { //当前出生
age = 0;
} else {
if (monthMinus < 0) { //不足周岁
age = age - 1;
}
if (monthMinus == 0) { //继续判断日期
if (dayMinus < 0) { //没满周岁
age = age - 1;
}
}
}
return age;
} else {
age1 = " ";
return age1;
}
}
/**
* 根据18位身份证号判断性别 15位再加判断
* @param idCard
* @return
*/
public static Object getSexFromCard(String idCard){
Integer sex; //1男 2女
String gender;
if (!StringUtils.isEmpty(idCard)) {
if (Integer.parseInt(idCard.substring(16).substring(0, 1)) % 2 == 0) { //判断性别
sex = 2; //女
} else {
sex = 1; //男
}
return sex;
} else {
gender =" ";
return gender;
}
}
}
逻辑很简单,知道身份证号码组成数字代表什么即可
身份证号组成说明可以看这里https://blog.csdn.net/qq_35501880/article/details/102716331