CredentialNumberUtil.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package com.xjrsoft.common.utils;
  2. import com.xjrsoft.common.exception.MyException;
  3. import java.time.LocalDate;
  4. import java.time.format.DateTimeFormatter;
  5. /**
  6. * 身份证号相关处理
  7. * @author dzx
  8. * @date 2025/4/1
  9. */
  10. public class CredentialNumberUtil {
  11. /**
  12. * 根据身份证号获取出生日期
  13. * @param idCardNumber 身份证号
  14. * @return 出生日期
  15. */
  16. public static LocalDate getBirthDate(String idCardNumber){
  17. // 获取出生日期前6位,即yyyyMM
  18. String birthdayString = idCardNumber.substring(6, 14);
  19. // 将字符串解析为LocalDate对象
  20. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
  21. try {
  22. LocalDate parse = LocalDate.parse(birthdayString, formatter);
  23. return parse;
  24. }catch (Exception e){
  25. throw new MyException("身份证号填写错误,无法提取出生日期");
  26. }
  27. }
  28. /**
  29. * 根据身份证号判断性别
  30. * @param idCard 身份证号码
  31. * @return "男" 或 "女"
  32. * @throws IllegalArgumentException 如果身份证号长度不正确
  33. */
  34. public static String getGenderByIdCard(String idCard) {
  35. if (idCard == null || (idCard.length() != 15 && idCard.length() != 18)) {
  36. throw new IllegalArgumentException("身份证号长度不正确");
  37. }
  38. // 15位身份证号:最后一位是性别位
  39. // 18位身份证号:第17位是性别位
  40. char genderChar;
  41. if (idCard.length() == 15) {
  42. genderChar = idCard.charAt(14);
  43. } else {
  44. genderChar = idCard.charAt(16);
  45. }
  46. // 将字符转换为数字
  47. int genderNum = Character.getNumericValue(genderChar);
  48. // 奇数男性,偶数女性
  49. return genderNum % 2 == 1 ? "男" : "女";
  50. }
  51. }