Java根据出生日期获取年龄
# 1、直接使用hutool工具类计算年龄
int age(Date begin,Date end) 表示出生到去世的年龄
int ageOfNow(String birthday) 计算到当前时间的年龄
int ageOfNow(Date birthday) 计算到当前时间的年龄
1
2
3
2
3
# 2、手搓 自己写
public Integer getAge(Date dateOfBirth) {
Integer age = 0;
Calendar born = Calendar.getInstance();
Calendar now = Calendar.getInstance();
if (dateOfBirth != null) {
now.setTime(new Date());
born.setTime(dateOfBirth);
if (born.after(now)) {
throw new IllegalArgumentException("年龄不能超过当前日期");
}
age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
int nowDayOfYear = now.get(Calendar.DAY_OF_YEAR);
int bornDayOfYear = born.get(Calendar.DAY_OF_YEAR);
if (nowDayOfYear < bornDayOfYear) {
age -= 1;
}
}
return age;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2023/03/17, 16:41:02