写一个java代码根据身份证获取出生年月日,性别,年龄
时间: 2023-03-29 20:03:13 浏览: 75
您好,根据您提供的问题,我可以回答。以下是Java代码示例:
```
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class IDCardUtil {
/**
* 根据身份证号获取出生年月日、性别、年龄
* @param idCard 身份证号
* @return String[],包含出生年月日、性别、年龄
*/
public static String[] getInfoByIdCard(String idCard) {
String[] info = new String[3];
String birthday = "";
String gender = "";
int age = ;
if (idCard.length() == 15) {
birthday = "19" + idCard.substring(6, 8) + "-" + idCard.substring(8, 10) + "-" + idCard.substring(10, 12);
gender = Integer.parseInt(idCard.substring(14, 15)) % 2 == ? "女" : "男";
} else if (idCard.length() == 18) {
birthday = idCard.substring(6, 10) + "-" + idCard.substring(10, 12) + "-" + idCard.substring(12, 14);
gender = Integer.parseInt(idCard.substring(16, 17)) % 2 == ? "女" : "男";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date birthDate = sdf.parse(birthday);
Calendar cal = Calendar.getInstance();
if (cal.before(birthDate)) {
throw new IllegalArgumentException("身份证号不正确!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDate);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH) + 1;
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
}
} else {
age--;
}
}
} catch (ParseException e) {
e.printStackTrace();
}
info[] = birthday;
info[1] = gender;
info[2] = String.valueOf(age);
return info;
}
}
```
使用示例:
```
public static void main(String[] args) {
String idCard = "110101199003077890";
String[] info = IDCardUtil.getInfoByIdCard(idCard);
System.out.println("出生年月日:" + info[]);
System.out.println("性别:" + info[1]);
System.out.println("年龄:" + info[2]);
}
```
输出结果:
```
出生年月日:199-03-07
性别:男
年龄:31
```
阅读全文