身份證獲取生日,性別,年齡演算法
import java.util.Calendar;
import java.util.regex.Pattern;
import com.zhongan.contacts.user.dto.ResultDTO;
/**
* 身份證演算法[計算性別,生日,年齡]
* @author daichangbo
*/
public class CertificateNoUtils {
public static ResultDTO parseCertificateNo(String certificateNo) {
ResultDTO resultDTO = new ResultDTO();
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}))$";
boolean valid=Pattern.matches(myRegExpIDCardNo,certificateNo)||(certificateNo.length() == 17 && Pattern.matches(myRegExpIDCardNo,certificateNo.substring(0,15)));
if(!valid){
resultDTO.setStatueMessage("證件號碼不規範!");
return resultDTO;
}
int idxSexStart = 16;
int birthYearSpan = 4;
//如果是15位的證件號碼
if(certificateNo.length() == 15) {
idxSexStart = 14;
birthYearSpan = 2;
}
//性別
String idxSexStr = certificateNo.substring(idxSexStart, idxSexStart + 1);
int idxSex = Integer.parseInt(idxSexStr) % 2;
String sex = (idxSex == 1) ? "M" : "F";
resultDTO.setSex(sex);
//出生日期
String year = (birthYearSpan == 2 ? "19" : "") + certificateNo.substring(6, 6 + birthYearSpan);
String month = certificateNo.substring(6 + birthYearSpan, 6 + birthYearSpan + 2);
String day = certificateNo.substring(8 + birthYearSpan, 8 + birthYearSpan + 2);
String birthday = year + '-' + month + '-' + day;
resultDTO.setBirthday(birthday);
//年齡
Calendar certificateCal = Calendar.getInstance();
Calendar currentTimeCal = Calendar.getInstance();
certificateCal.set(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day));
int yearAge = (currentTimeCal.get(currentTimeCal.YEAR)) - (certificateCal.get(certificateCal.YEAR));
certificateCal.set(currentTimeCal.get(Calendar.YEAR), Integer.parseInt(month)-1, Integer.parseInt(day));
int monthFloor = (currentTimeCal.before(certificateCal) ? 1 : 0);
resultDTO.setAge(yearAge - monthFloor);
return resultDTO;
}
}