java校验身份证是否正确并按照身份证获取年龄 月份 天数 性别
时间: 2023-05-17 17:04:11 浏览: 93
JAVA版身份证获取性别、出生日期及年龄
5星 · 资源好评率100%
可以使用Java中的正则表达式来校验身份证号码是否正确,然后根据身份证号码中的出生日期计算年龄、月份、天数和性别。以下是一个示例代码:
```java
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IdCardUtils {
/**
* 校验身份证号码是否正确
*
* @param idCard 身份证号码
* @return 是否正确
*/
public static boolean isValidIdCard(String idCard) {
String regex = "(\\d{17}[0-9a-zA-Z]|\\d{14}[0-9a-zA-Z])";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(idCard);
if (!matcher.matches()) {
return false;
}
// 校验码验证
if (idCard.length() == 18) {
int[] weights = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
String[] codes = new String[]{"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
int sum = 0;
for (int i = 0; i < 17; i++) {
sum += (idCard.charAt(i) - '0') * weights[i];
}
int index = sum % 11;
if (!codes[index].equals(idCard.substring(17))) {
return false;
}
}
return true;
}
/**
* 根据身份证号码获取年龄、月份、天数和性别
*
* @param idCard 身份证号码
* @return 年龄、月份、天数和性别
*/
public static IdCardInfo getIdCardInfo(String idCard) {
IdCardInfo idCardInfo = new IdCardInfo();
if (!isValidIdCard(idCard)) {
return idCardInfo;
}
String birthday = "";
if (idCard.length() == 18) {
birthday = idCard.substring(6, 14);
} else if (idCard.length() == 15) {
birthday = "19" + idCard.substring(6, 12);
}
int year = Integer.parseInt(birthday.substring(0, 4));
int month = Integer.parseInt(birthday.substring(4, 6));
int day = Integer.parseInt(birthday.substring(6));
Calendar calendar = Calendar.getInstance();
int currentYear = calendar.get(Calendar.YEAR);
int currentMonth = calendar.get(Calendar.MONTH) + 1;
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
int age = currentYear - year;
int monthDiff = currentMonth - month;
int dayDiff = currentDay - day;
if (monthDiff < 0 || (monthDiff == 0 && dayDiff < 0)) {
age--;
}
idCardInfo.setAge(age);
idCardInfo.setMonth(month);
idCardInfo.setDay(day);
int gender = idCard.charAt(idCard.length() - 2) - '0';
idCardInfo.setGender(gender % 2 == 1 ? "男" : "女");
return idCardInfo;
}
public static class IdCardInfo {
private int age;
private int month;
private int day;
private String gender;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "IdCardInfo{" +
"age=" + age +
", month=" + month +
", day=" + day +
", gender='" + gender + '\'' +
'}';
}
}
}
```
使用示例:
```java
String idCard = "110101199003077777";
IdCardUtils.IdCardInfo idCardInfo = IdCardUtils.getIdCardInfo(idCard);
System.out.println(idCardInfo);
```
输出结果:
```
IdCardInfo{age=31, month=3, day=7, gender='男'}
```
阅读全文