我想在 Java 方法中以 int 形式返回年龄.我现在拥有的是以下内容,其中 getBirthDate() 返回一个 Date 对象(带有出生日期;-)):
I want to return an age in years as an int in a Java method. What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)):
public int getAge() {
long ageInMillis = new Date().getTime() - getBirthDate().getTime();
Date age = new Date(ageInMillis);
return age.getYear();
}
但是由于 getYear() 已被弃用,我想知道是否有更好的方法来做到这一点?我什至不确定这是否能正常工作,因为我还没有进行单元测试.
But since getYear() is deprecated I'm wondering if there is a better way to do this? I'm not even sure this works correctly, since I have no unit tests in place (yet).
JDK 8 让这一切变得简单而优雅:
JDK 8 makes this easy and elegant:
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 测试来演示它的使用:
A JUnit test to demonstrate its use:
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.所有早期版本均已结束其支持生命周期.
Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.
这篇关于如何在 Java 中计算某人的年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!