根据身份证号判断性别、年龄、生日

根据身份证号判断证件持有人的性别、年龄、生日。废话不多说,直接上代码。

public class IdentifyCard {
    private static final Integer[] ODD_NUMS = {1, 3, 5, 7, 9};
    private static final Integer[] EVEN_NUMS = {0, 2, 4, 6, 8};

    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT_THREAD_LOCAL =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd"));
    
    /**
     * @param area     地区码,如:110101
     * @param birthday 出生日期:20000101
     * @param sex      性别:0=男;1=女
     * @param size     最小1;最大500
     * @return results 生成结果集
     */
    public static String[] generator(String area, Date birthday, int sex, int size) {
        SexEnum.checkSex(sex);
        checkSize(size);
        List<String> resultList = new ArrayList<>(size);
        String simpleBirthday = DATE_FORMAT_THREAD_LOCAL.get().format(birthday);
        Set<String> numbers = ordinalNumbers(sex, size);
        for (String seqNo : numbers) {
            String prefix = area + simpleBirthday + seqNo;
            String cardNo = prefix + getCheckCode(prefix);
            resultList.add(cardNo);
        }
        String[] results = resultList.toArray(new String[size]);
        new RandomSort<String>(results).changePosition();
        return results;
    }

    private static void checkSize(int size) {
        if (size < 1 || size > 500) {
            throw new IllegalArgumentException("The size min 1, max 500.");
        }
    }

    // prefix = area + birthdayFormat + seqNo
    private static String getCheckCode(String prefix) {
        int sum = 0;
        for (int i = 0; i < prefix.length(); i++) {
      
### Python根据身份证号计算年龄的方法 以下是通过Python实现根据身份证号计算年龄的功能代码: ```python import datetime def calculate_age_by_id_card(id_card): today = datetime.date.today() birth_year = int(id_card[6:10]) birth_month = int(id_card[10:12]) birth_day = int(id_card[12:14]) age = today.year - birth_year - ((today.month, today.day) < (birth_month, birth_day)) gender = "女" if int(id_card[-2]) % 2 == 0 else "男" birthday = f"{birth_year}年{birth_month}月{birth_day}日" return { "birthday": birthday, "age": age, "gender": gender } id_card = input("请输入一个有效的身份证号:") if len(id_card) != 18 or not id_card.isdigit(): print("输入的身份证号不合法!") else: result = calculate_age_by_id_card(id_card) print(f"您生于{result['birthday']},性别为{result['gender']}") print(f"您的年龄为:{result['age']}岁") ``` 此代码实现了以下功能: - 提取身份证号中的生年月日信息[^2]。 - 判断当前日期与生日期的关系来精确计算年龄[^2]。 - 根据身份证号第17位判断性别[^2]。 #### 关键点说明 1. **身份证号合法性校验** 身份证号长度应为18位且全部由数字组成。如果不符合该条件,则提示用户重新输入。 2. **年龄计算逻辑** 年龄等于当前年份减去生年份,再根据当前日期是否已过生日调整最终结果[^2]。 3. **性别判定** 使用身份证号倒数第二位(即第17位),如果是偶数则表示女性;奇数表示男性[^2]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值