package com.cm.common.utils.card;

import javax.validation.constraints.NotNull;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * @version 1.0
 * @className IdCardUtil
 * @description 身份证
 * @date 2018/9/3 12:22
 **/
public class IdCardUtil {

    private static final Pattern PATTERN_ID_CARD = Pattern.compile("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");

    /**
     * 校验身份证
     *
     * @param idCard
     * @return
     */
    public static boolean isIdCard(String idCard) {
        return PATTERN_ID_CARD.matcher(idCard).matches();
    }

    /**
     * 获取生日
     *
     * @param idCard
     * @return
     */
    @NotNull
    public static String getBirthday(String idCard) {
        if (null == idCard) {
            return null;
        }
        String birth = idCard.substring(6, 14);
        String year = birth.substring(0, 4);
        String month = birth.substring(4, 6);
        String day = birth.substring(6, 8);
        return year + "-" + month + "-" + day;
    }

    /**
     * 获取性别
     *
     * @param idCard
     * @return
     */
    @NotNull
    public static String getSex(String idCard) {
        if (null == idCard) {
            return null;
        }
        int sexNum = Integer.parseInt(idCard.substring(16, 17));
        if (sexNum % 2 == 0) {
            return "女";
        }
        return "男";
    }

    public static void main(String[] args) {
        System.out.println(IdCardUtil.getBirthday("142201199101290010"));
        System.out.println(IdCardUtil.getSex("142201199101290010"));
    }
}
