使用java编写18位身份证码获取生日,年龄,性别具体功能实现方法
时间: 2024-06-10 07:09:13 浏览: 8
您好!对于您的问题,我可以给您提供一个Java代码示例来获取身份证的生日、年龄和性别信息。请参考以下代码:
```
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class IdCardUtil {
/**
* 通过身份证号码获取出生日期、年龄、性别
* @param idCard 身份证号码
* @return 生日、年龄、性别信息的数组,其中:
* [0]表示生日,格式为"yyyy-MM-dd"
* [1]表示年龄
* [2]表示性别,其中1表示男性,2表示女性
*/
public static String[] getIdCardInfo(String idCard) {
String[] info = new String[3];
if (idCard == null || idCard.length() != 18) {
return null;
}
String birthday = idCard.substring(6, 14);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
try {
Date birthDate = sdf1.parse(birthday);
info[0] = sdf2.format(birthDate);
Calendar cal = Calendar.getInstance();
if (cal.before(birthDate)) {
return null;
}
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);
int age = yearNow - yearBirth;
if (monthNow < monthBirth || (monthNow == monthBirth && dayOfMonthNow < dayOfMonthBirth)) {
age--;
}
info[1] = String.valueOf(age);
int gender = Integer.parseInt(idCard.substring(16, 17));
info[2] = gender % 2 == 0 ? "2" : "1";
} catch (Exception e) {
e.printStackTrace();
}
return info;
}
}
```
使用该方法,您可以方便地获取到身份证的生日、年龄和性别等信息。当然,如果您有其他的问题,也可以随时向我提问哦!
相关推荐
![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)