package com.ruzhoukj.sms.util; import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; public class IDCardUtils { /** * 从身份证号中提取出生日期 * * @param idCard 身份证号 * @return 出生日期(LocalDate) */ public static LocalDate getBirthDate(String idCard) { if (idCard == null || idCard.length() != 18) { throw new IllegalArgumentException("身份证号格式不正确"); } String birthDateStr = idCard.substring(6, 14); // 提取出生日期部分 try { return LocalDate.parse(birthDateStr, DateTimeFormatter.ofPattern("yyyyMMdd")); } catch (DateTimeParseException e) { throw new IllegalArgumentException("身份证号中的出生日期格式不正确"); } } /** * 从身份证号中提取生日 * * @param birthDate 出生日期 * @return 生日 */ public static String getBirth(LocalDate birthDate) { return birthDate.getMonthValue() + "-" + birthDate.getDayOfMonth(); } /** * 计算年龄 * * @param birthDate 出生日期(LocalDate) * @return 年龄 */ public static int calculateAge(LocalDate birthDate) { if (birthDate == null) { throw new IllegalArgumentException("出生日期不能为空"); } LocalDate currentDate = LocalDate.now(); return Period.between(birthDate, currentDate).getYears(); } public static void main(String[] args) { String idCard = "320311198705281234"; // 示例身份证号 try { LocalDate birthDate = getBirthDate(idCard); // 提取出生日期 System.out.println("出生日期: " + birthDate); String birth = getBirth(birthDate); // 提取出生日期 System.out.println("生日: " + birth); DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String formattedDate1 = birthDate.format(formatter1); System.out.println("格式化后的日期 (yyyy-MM-dd): " + formattedDate1); int age = calculateAge(birthDate); // 计算年龄 System.out.println("年龄: " + age); } catch (IllegalArgumentException e) { System.err.println("错误: " + e.getMessage()); } } }