根据生日计算当前年龄
chen subao Lv1

时间类型采用LocalDate进行计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 根据生日计算年龄
* @param birthday 生日时间,出生时间 {@link LocalDate}
* @return 具体的年龄
*/
private int calculateAge(LocalDate birthday) {
// LocalDate now = LocalDate.now();
LocalDate now = LocalDate.of(2021, 3, 5);
// 生日日期大于现在日期
if (null == birthday || birthday.compareTo(now) > 0) {
return -1;
}
// 现在的年份减去生日的年份
int age = now.getYear() - birthday.getYear();
int compareValue = now.getMonth().compareTo(birthday.getMonth());
// 当前月份小于生日月份 或 当前月份等于生日月份且当前日期小于生日日期
if (compareValue < 0 ||
(compareValue == 0 && now.getDayOfMonth() < birthday.getDayOfMonth())) {
return age - 1;
}
return age;
}

测试结果

1
2
3
4
5
6
7
8
9
10
@Test
public void t1() {
System.out.println(calculateAge(LocalDate.of(2021, 3, 4))); // 0
System.out.println(calculateAge(LocalDate.of(1999, 3, 4))); // 22
System.out.println(calculateAge(LocalDate.of(2021, 4, 4))); // -1
System.out.println(calculateAge(LocalDate.of(2021, 3, 6))); // -1
System.out.println(calculateAge(LocalDate.of(1999, 3, 6))); // 21
System.out.println(calculateAge(LocalDate.of(2021, 3, 5))); // 0
System.out.println(calculateAge(LocalDate.of(1999, 3, 5))); // 22
}
 评论