将身份证号转换为年龄

/**
* 将身份证号转换为年龄
* @param idCard 身份证号
* @return 年龄字符串
*/
public static int idCard2Age(String idCard) {
if (idCard == null) {
return null;
}
if (idCard.length() == 15) {
idCard = idCard.substring(0, 6) + "19" + idCard.substring(6, 15);
}
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = (now.get(Calendar.MONTH) + 1);
int day = now.get(Calendar.DAY_OF_MONTH);
int age = year - Integer.parseInt(idCard.substring(6, 10)) - 1;
if (Integer.parseInt(idCard.substring(10, 12)) < month
|| Integer.parseInt(idCard.substring(10, 12)) == month
&& Integer.parseInt(idCard.substring(12, 14)) <= day) {
age++;
}
return age;
}
posted @ 2021-11-16 11:09  游走人间的蒲公英  阅读(382)  评论(0编辑  收藏  举报