写段Java代码通过身份证号码解析出年龄,性别,生日
时间: 2023-05-19 19:01:47 浏览: 153
以下是Java代码,可以通过身份证号码解析出年龄,性别和生日:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class IdCardParser {
public static void main(String[] args) {
String idCard = "110101199003077777";
String birthday = getBirthday(idCard);
String gender = getGender(idCard);
int age = getAge(idCard);
System.out.println("Birthday: " + birthday);
System.out.println("Gender: " + gender);
System.out.println("Age: " + age);
}
public static String getBirthday(String idCard) {
String birthday = "";
if (idCard.length() == 18) {
birthday = idCard.substring(6, 14);
} else if (idCard.length() == 15) {
birthday = "19" + idCard.substring(6, 12);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
Date date = sdf.parse(birthday);
birthday = sdf.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return birthday;
}
public static String getGender(String idCard) {
String gender = "";
if (idCard.length() == 18) {
gender = idCard.substring(16, 17);
} else if (idCard.length() == 15) {
gender = idCard.substring(14, 15);
}
int genderNum = Integer.parseInt(gender);
if (genderNum % 2 == 0) {
return "Female";
} else {
return "Male";
}
}
public static int getAge(String idCard) {
int age = 0;
Calendar calendar = Calendar.getInstance();
int currentYear = calendar.get(Calendar.YEAR);
int birthYear = 0;
if (idCard.length() == 18) {
birthYear = Integer.parseInt(idCard.substring(6, 10));
} else if (idCard.length() == 15) {
birthYear = Integer.parseInt("19" + idCard.substring(6, 8));
}
age = currentYear - birthYear;
return age;
}
}
```
注意:这段代码只是一个简单的示例,实际应用中需要考虑更多的情况,比如身份证号码的合法性等。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)