廢話不多少,直接上代碼,喜歡點個贊!
/**
* 根據身份證獲取年齡,性別,生日
* @param idNum
* @return
* @author
*/
public static Map<String, String> getAgeAndSexById(String idNum) {
String age = "";
String sex = "";
String bir = "";
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getDefault());//獲取系統當前時間
int currentYear = calendar.get(Calendar.YEAR);
if (idNum.matches("^\\d{15}$|^\\d{17}[\\dxX]$")) {
if (idNum.length() == 18) {
Pattern pattern = Pattern.compile("\\d{6}(\\d{4})\\d{6}(\\d{1})[\\dxX]{1}");
Matcher matcher = pattern.matcher(idNum);
if (matcher.matches()) {
age = String.valueOf(currentYear - Integer.parseInt(matcher.group(1)));
sex = Integer.parseInt(matcher.group(2))%2==0?"2":"1";
bir = idNum.substring(6, 10)+"-"
+ idNum.substring(10, 12)+"-"
+ idNum.substring(12, 14);
}
} else if (idNum.length() == 15) {
Pattern p = Pattern.compile("\\d{6}(\\d{2})\\d{5}(\\d{1})\\d{1}");
Matcher m = p.matcher(idNum);
if (m.matches()) {
int year = Integer.parseInt(m.group(1));
year = 2000 + year;
if (year > 2020) {
year = year - 100;
}
age = String.valueOf(currentYear - year);
sex = Integer.parseInt(m.group(2))%2==0?"2":"1";
bir = "19" + idNum.substring(6, 8)+"-"
+ idNum.substring(8, 10) +"-"
+ idNum.substring(10, 12);
}
}
}
Map<String, String> reMap = new HashMap<String, String>();
reMap.put("age", age);
reMap.put("sex", sex);
reMap.put("bir", bir);
return reMap;
}