java按照身份证获取年龄 月份 天数 性别
时间: 2023-05-17 17:04:08 浏览: 102
C# 获取当前月份天数的三种方法总结
可以使用Java中的SimpleDateFormat类和Calendar类来实现按照身份证获取年龄、月份、天数和性别的功能。具体实现方法可以参考以下代码:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class IdCardUtil {
/**
* 根据身份证号获取年龄、月份、天数和性别
* @param idCard 身份证号
* @return 返回一个数组,依次为年龄、月份、天数和性别
*/
public static int[] getAgeMonthDaySexByIdCard(String idCard) {
int[] result = new int[4];
if (idCard == null || idCard.length() != 18) {
return result;
}
String birthdayStr = idCard.substring(6, 14);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date birthday = null;
try {
birthday = sdf.parse(birthdayStr);
} catch (Exception e) {
e.printStackTrace();
}
if (birthday == null) {
return result;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(birthday);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
result[0] = getAge(year, month, day);
result[1] = month;
result[2] = day;
result[3] = getSex(idCard);
return result;
}
/**
* 根据出生年月日计算年龄
* @param year 出生年份
* @param month 出生月份
* @param day 出生日期
* @return 返回年龄
*/
private static int getAge(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
int nowYear = calendar.get(Calendar.YEAR);
int nowMonth = calendar.get(Calendar.MONTH) + 1;
int nowDay = calendar.get(Calendar.DAY_OF_MONTH);
int age = nowYear - year;
if (nowMonth < month || (nowMonth == month && nowDay < day)) {
age--;
}
return age;
}
/**
* 根据身份证号获取性别
* @param idCard 身份证号
* @return 返回性别,1表示男性,2表示女性
*/
private static int getSex(String idCard) {
int sex = 0;
if (idCard.length() == 15) {
sex = idCard.charAt(14) - '0';
} else if (idCard.length() == 18) {
sex = idCard.charAt(16) - '0';
}
if (sex % 2 == 0) {
return 2;
} else {
return 1;
}
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) {
String idCard = "110101199003077890";
int[] result = IdCardUtil.getAgeMonthDaySexByIdCard(idCard);
System.out.println("年龄:" + result[0]);
System.out.println("月份:" + result[1]);
System.out.println("天数:" + result[2]);
System.out.println("性别:" + result[3]);
}
}
```
输出结果:
```
年龄:31
月份:3
天数:7
性别:1
```
阅读全文