liujie
2026-01-22 d993c7e4c1b9fc0b41ea7dbd4e8e997ca60a5af9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.ruoyi.system.utils.util;
 
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
 
public class IDCardAgeCalculator {
 
    public static int calculateAge(String idCard) {
        // 检查身份证号码是否为18位
        if (idCard == null || idCard.length() != 18) {
            throw new IllegalArgumentException("身份证号码必须为18位");
        }
        
        // 解析出生日期
        String birthDateStr = idCard.substring(6, 14); // 获取出生日期部分
        LocalDate birthDate = LocalDate.parse(birthDateStr, DateTimeFormatter.ofPattern("yyyyMMdd"));
        
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        
        // 计算年龄
        Period period = Period.between(birthDate, currentDate);
        int age = period.getYears(); // 直接获取年份差即为年龄
        
        return age;
    }
    
    public static void main(String[] args) {
        String idCard = "110105194912311234"; // 示例身份证号码
        try {
            int age = calculateAge(idCard);
            System.out.println("年龄: " + age);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}