java 根据身份证年月日计算年龄
时间: 2024-11-13 08:41:36 浏览: 37
在Java中,计算一个人的年龄通常需要获取当前日期并与出生日期进行比较。以下是基于`java.time.LocalDate`类的一个简单示例:
```java
import java.time.LocalDate;
import java.time.Period;
public class AgeCalculator {
public static int calculateAge(LocalDate birthDate) {
LocalDate currentDate = LocalDate.now(); // 获取当前日期
Period agePeriod = Period.between(birthDate, currentDate); // 计算两个日期之间的差值
return agePeriod.getYears(); // 返回整年的年龄,不考虑月份和日子
}
public static void main(String[] args) {
String idCardInfo = "19900101"; // 示例的身份证号格式,实际应用中需解析
int year = Integer.parseInt(idCardInfo.substring(6, 10)); // 提取年份
int month = Integer.parseInt(idCardInfo.substring(4, 6));
int day = Integer.parseInt(idCardInfo.substring(0, 2));
LocalDate birthDate = LocalDate.of(year, month, day);
int age = calculateAge(birthDate);
System.out.println("年龄:" + age + "岁");
}
}
```
这个代码首先从身份证号字符串中提取出年、月、日信息,然后创建一个`LocalDate`对象表示出生日期。接着,它计算出生日期和当前日期之间的时间差,并返回年龄(忽略天数)。如果你需要精确到月或日,可以考虑添加额外的逻辑。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)