1. 程式人生 > >java通過身份證號碼獲取出生日期、性別、年齡

java通過身份證號碼獲取出生日期、性別、年齡

身份證號碼:

15位:6位地址碼+6位出生年月日(900101代表1990年1月1日出生)+3位順序碼
18位:6位地址碼+8位出生年月日(19900101代表1990年1月1日出生)+3位順序碼+1位校驗碼

地區碼:

1、 第一、二位表示省(自治區、直轄市、特別行政區)。
2、 第三、四位表示市(地級市、自治州、盟及國家直轄市所屬市轄區和縣的彙總碼)。其中,01-20,51-70表示省直轄市;21-50表示地區(自治州、盟)。
3、 第五、六位表示縣(市轄區、縣級市、旗)。01-18表示市轄區或地區(自治州、盟)轄縣級市;21-80表示縣(旗);81-99表示省直轄縣級市。

順序碼:

順序碼奇數分給男性,偶數分給女性。

校驗碼:

作為尾號的校驗碼,是由號碼編制單位按統一的公式計算出來的,如果某人的尾號是0-9,都不會出現X,但如果尾號是10,那麼就得用X來代替,因為如果用10做尾號,那麼此人的身份證就變成了19位,而19位的號碼違反了國家標準,並且中國的計算機應用系統也不承認19位的身份證號碼。Ⅹ是羅馬數字的10,用X來代替10,可以保證公民的身份證符合國家標準。

程式碼:


    /**
     * 通過身份證號碼獲取出生日期、性別、年齡
     * @param certificateNo
     * @return 返回的出生日期格式:1990-01-01   性別格式:F-女,M-男
     */
    public static Map<String, String> getBirAgeSex(String certificateNo) {
        String birthday = ""
; String age = ""; String sexCode = ""; int year = Calendar.getInstance().get(Calendar.YEAR); char[] number = certificateNo.toCharArray(); boolean flag = true; if (number.length == 15) { for (int x = 0; x < number.length; x++) { if
(!flag) return new HashMap<String, String>(); flag = Character.isDigit(number[x]); } } else if (number.length == 18) { for (int x = 0; x < number.length - 1; x++) { if (!flag) return new HashMap<String, String>(); flag = Character.isDigit(number[x]); } } if (flag && certificateNo.length() == 15) { birthday = "19" + certificateNo.substring(6, 8) + "-" + certificateNo.substring(8, 10) + "-" + certificateNo.substring(10, 12); sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "F" : "M"; age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + ""; } else if (flag && certificateNo.length() == 18) { birthday = certificateNo.substring(6, 10) + "-" + certificateNo.substring(10, 12) + "-" + certificateNo.substring(12, 14); sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "F" : "M"; age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + ""; } Map<String, String> map = new HashMap<String, String>(); map.put("birthday", birthday); map.put("age", age); map.put("sexCode", sexCode); return map; }