問題描述
我想在 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模板網!