【工具】- 证件类篇

  • 日常开发中会需要使用一些证件类的处理的工具类
@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;
    }
原文地址:https://www.cnblogs.com/lycsmzl/p/13408583.html