gpt4 book ai didi

java - 如何用Java计算某人的年龄?

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:38 25 4
gpt4 key购买 nike

我想在 Java 方法中以 int 形式返回年龄(以年为单位)。我现在所拥有的是以下内容,其中 getBirthDate() 返回一个 Date 对象(带有出生日期;-)):

public int getAge() {
long ageInMillis = new Date().getTime() - getBirthDate().getTime();

Date age = new Date(ageInMillis);

return age.getYear();
}

但是由于 getYear() 已被弃用,我想知道是否有更好的方法来做到这一点?我什至不确定这是否正确,因为我还没有单元测试。

最佳答案

JDK 8 使这一切变得简单而优雅:

public class AgeCalculator {

public static int calculateAge(LocalDate birthDate, LocalDate currentDate) {
if ((birthDate != null) && (currentDate != null)) {
return Period.between(birthDate, currentDate).getYears();
} else {
return 0;
}
}
}

演示其用途的 JUnit 测试:

public class AgeCalculatorTest {

@Test
public void testCalculateAge_Success() {
// setup
LocalDate birthDate = LocalDate.of(1961, 5, 17);
// exercise
int actual = AgeCalculator.calculateAge(birthDate, LocalDate.of(2016, 7, 12));
// assert
Assert.assertEquals(55, actual);
}
}

现在每个人都应该使用 JDK 8。所有早期版本均已结束支持期限。

关于java - 如何用Java计算某人的年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55094600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com