文章 49
评论 20
浏览 81339
身份证工具类

身份证工具类

记录身份证工具类


import java.time.LocalDateTime;

import static java.lang.Integer.parseInt;

public class IdentityCardUtils {

    /**
     * 获取年
     *
     * @param idNumber
     * @return
     */
    public static int getYear(String idNumber) {
        if (idNumber.length() == 15) {
            return parseInt("19" + idNumber.substring(6, 8));
        }
        return parseInt(idNumber.substring(6, 10));
    }

    /**
     * 获取月
     *
     * @param idNumber
     * @return
     */
    public static int getMonth(String idNumber) {
        if (idNumber.length() == 15) {
            return parseInt(idNumber.substring(8, 10));
        }
        return parseInt(idNumber.substring(10, 12));
    }

    /**
     * 获取日
     *
     * @param idNumber
     * @return
     */
    public static int getDay(String idNumber) {
        if (idNumber.length() == 15) {
            return parseInt(idNumber.substring(10, 12));
        }
        return parseInt(idNumber.substring(12, 14));
    }

    /**
     * 获取出生年月日
     *
     * @param idNumber
     * @return
     */
    public static String getYearMonthDay(String idNumber) {
        if (idNumber.length() == 15) {
            return "19" + idNumber.substring(6, 12);
        }
        return idNumber.substring(6, 14);
    }

    /**
     * 获取指定格式化之后的出生年月日
     *
     * @param idNumber
     * @return
     */
    public static String getFormatYMD(String idNumber, String format) {
        int year = IdentityCardUtils.getYear(idNumber);
        int month = IdentityCardUtils.getMonth(idNumber);
        int day = IdentityCardUtils.getDay(idNumber);
        return new StringBuffer(String.valueOf(year)).append(format).append(month).append(format).append(day).toString();
    }

    /**
     * 获取性别
     *
     * @param idNumber 1:男 0:女
     * @return
     */
    public static int getSex(String idNumber) {
        String val = null;
        if (idNumber.length() == 15) {
            val = idNumber.substring(14, 15);
        } else if (idNumber.length() == 18) {
            val = idNumber.substring(16, 17);
        }
        assert val != null;
        if (Integer.parseInt(val) % 2 == 0) {
            return 0;
        } else {
            return 1;
        }
    }

    public static String getSexString(String idNumber) {
        return getSex(idNumber) == 0 ? "女" : "男";
    }

    /**
     * 获取年龄
     *
     * @param idNumber
     * @return
     */
    public static int getAge(String idNumber) {
        int currentYear = LocalDateTime.now().getYear();
        int age = currentYear - getYear(idNumber);
        int month = getMonth(idNumber);
        int currentMonth = LocalDateTime.now().getMonthValue();
        if (month > currentMonth) {
            --age;
        }
        return age;
    }

}

哈哈哈哈哈哈哈嗝~

取消