JAVA 根据身份证号码解析出生日期、性别、年龄

  1. public class CertificateNo {    
  2. public ResultDTO parseCertificateNo(String certificateNo) {  
  3.           
  4.         ResultDTO resultDTO = new ResultDTO();  
  5.         String myRegExpIDCardNo = "^\d{6}(((19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}([0-9]|x|X))|(\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}))$";  
  6.         boolean valid=Pattern.matches(myRegExpIDCardNo,certificateNo)||(certificateNo.length() == 17 && Pattern.matches(myRegExpIDCardNo,certificateNo.substring(0,15)));  
  7.         if(!valid){  
  8.             resultDTO.setStatueMessage("证件号码不规范!");  
  9.             return resultDTO;  
  10.         }  
  11.         int idxSexStart = 16;  
  12.         int birthYearSpan = 4;  
  13.         //如果是15位的证件号码  
  14.         if(certificateNo.length() == 15) {  
  15.             idxSexStart = 14;  
  16.             birthYearSpan = 2;  
  17.         }  
  18.           
  19.         //性别  
  20.         String idxSexStr = certificateNo.substring(idxSexStart, idxSexStart + 1);  
  21.         int idxSex = Integer.parseInt(idxSexStr) % 2;  
  22.         String sex = (idxSex == 1) ? "M" : "F";  
  23.         resultDTO.setSex(sex);  
  24.           
  25.         //出生日期  
  26.         String year = (birthYearSpan == 2 ? "19" : "") + certificateNo.substring(6, 6 + birthYearSpan);  
  27.         String month = certificateNo.substring(6 + birthYearSpan, 6 + birthYearSpan + 2);  
  28.         String day = certificateNo.substring(8 + birthYearSpan, 8 + birthYearSpan + 2);  
  29.         String birthday = year + '-' + month + '-' + day;  
  30.         resultDTO.setBirthday(birthday);  
  31.           
  32.         //年龄  
  33.         Calendar certificateCal = Calendar.getInstance();  
  34.         Calendar currentTimeCal = Calendar.getInstance();  
  35.         certificateCal.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day));  
  36.         int yearAge = (currentTimeCal.get(currentTimeCal.YEAR)) - (certificateCal.get(certificateCal.YEAR));  
  37.         certificateCal.set(currentTimeCal.get(Calendar.YEAR), Integer.parseInt(month)-1, Integer.parseInt(day));  
  38.         int monthFloor = (currentTimeCal.before(certificateCal) ? 1 : 0);  
  39.         resultDTO.setAge(yearAge - monthFloor);  
  40.           
  41.         return resultDTO;  
  42.     }  
  43. }
原文地址:https://www.cnblogs.com/DylanZ/p/12979085.html