1. 程式人生 > 實用技巧 >【工具】- 證件類篇

【工具】- 證件類篇

  • 日常開發中會需要使用一些證件類的處理的工具類
@Slf4j
public class IdCardNoUtils {

    private static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

    /**
     *18位身份證號碼: 第17位代表性別,奇數為男,偶數為女
     * @param idCardNo
     * @return
     */
    public static String getSex(String idCardNo) {
        if (idCardNo == null || idCardNo.length() != 18) {
            return "";
        }
        char c = idCardNo.charAt(16);
        int sex = Integer.valueOf(c);
        return sex % 2 == 0 ? "女" : "男";
    }

    /**
     *18位身份證號碼: 第7-14位代表yyyyMMdd
     * @param idCardNo
     * @return
     */
    public static Date getBirthday(String idCardNo) {
        if (idCardNo == null || idCardNo.length() != 18) {
            throw new BusinessException("身份證格式有誤!");
        }
        String birthdayStr = idCardNo.substring(6, 14);
        Date birthday = null;
        try {
            birthday = formatter.parse(birthdayStr);
        } catch (ParseException e) {
            log.warn("日期格式轉化錯誤! birthday:" + birthday, e);
        }
        return birthday;
    }

    /**
     *18位身份證號碼: 第7-14位代表yyyyMMdd,可用來計算年齡
     * @param idCardNo
     * @return
     */
    public static int getAge(String idCardNo) {
        if (idCardNo == null || idCardNo.length() != 18) {
            return -1;
        }
        String birthday = idCardNo.substring(6, 14);
        Date birthdayDate = null;
        try {
            birthdayDate = formatter.parse(birthday);
        } catch (ParseException e) {
            log.warn("日期格式轉化錯誤! birthday:" + birthday, e);
        }
        return getAgeByDate(birthdayDate);
    }

    /**
     * 計算年齡,精確到天
     * @param birthday
     * @return
     */
    private static int getAgeByDate(Date birthday) {
        Calendar calendar = Calendar.getInstance();
        if (calendar.getTimeInMillis() - birthday.getTime() < 0L) {
            return -1;
        }
        //當前的年月日
        int yearNow = calendar.get(Calendar.YEAR);
        int monthNow = calendar.get(Calendar.MONTH);
        int dayNow = calendar.get(Calendar.DAY_OF_MONTH);
        //生日的年月日
        calendar.setTime(birthday);
        int yearBirthday = calendar.get(Calendar.YEAR);
        int monthBirthday = calendar.get(Calendar.MONTH);
        int dayBirthday = calendar.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirthday;
        //月份或日子沒滿
        if (monthNow < monthBirthday || (monthNow == monthBirthday && dayNow < dayBirthday)) {
            age = age - 1;
        }
        return age;
    }