1. 程式人生 > >java8 通過18位身份證號提取使用者資訊(年齡,生日,姓別)

java8 通過18位身份證號提取使用者資訊(年齡,生日,姓別)

工作中經常用到的通過身份證號(18位)提取使用者資訊(年齡,生日,姓別),分享給大家:

先做一個javabean 存使用者資訊:

package com;

import lombok.*;

import java.time.LocalDate;

/**
 * @author kevin
 * Date 2018/9/5
 * Time 9:34
 */
@Builder
@Data
public class IdentityCard {

    /**
     * 身份證號
     */
    private String ID;
    private Sex sex;
    private LocalDate birthday;
    private long age;


    @ToString
    @Getter
    public enum Sex {
        MALE(1, "男"), FEMALE(2, "女");

        private int code;
        private String value;

        Sex(int code, String value) {
            this.code = code;
            this.value = value;
        }
    }
}

再寫一個提取工具類:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author kevin
 * Date 2018/9/5
 * Time 9:47
 */
public interface IdentityCardUtil {
    Pattern pattern = 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 id 解析出使用者的基本資訊
     *
     * @param id 18位身份證號
     * @return IdentityCard
     */
    static IdentityCard extIdentityInfo(String id) {
        String exceptionMsg = Objects.requireNonNull(id, "身份證號不能為空");
        if (Objects.equals(id, "")) {
            throw new IllegalArgumentException(exceptionMsg);
        }
        Matcher matcher = pattern.matcher(id);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("身份證號碼不合法");
        }

        String birthdayStr = id.substring(6, 14);
        LocalDate birthday = LocalDate.from(DateTimeFormatter.ofPattern("yyyyMMdd").parse(birthdayStr));
        long age = ChronoUnit.YEARS.between(birthday, LocalDate.now());
        IdentityCard identityCard = IdentityCard.builder().ID(id).birthday(birthday).age(age).build();
        if (Integer.parseInt(id.substring(16).substring(0, 1)) % 2 == 0) {
            identityCard.setSex(IdentityCard.Sex.FEMALE);
        } else {
            identityCard.setSex(IdentityCard.Sex.MALE);
        }
        return identityCard;

    }

}

基本使用方法:

package com.test.java8.identity;

/**
 * @author kevin
 * Date 2018/9/5
 * Time 10:52
 */
public class Test {
    public static void main(String[] args) {


        IdentityCard card = IdentityCardUtil.extIdentityInfo("130724198108204342");

        System.out.println(card.toString());
        System.out.println(card.getSex().getCode());
        System.out.println(card.getAge());


    }
}