问题
我希望在Java方法中将年龄作为int返回。我现在有以下内容:getBirthDate()返回Date对象(出生日期;-)):
public int getAge() {
long ageInMillis = new Date().getTime() - getBirthDate().getTime();
Date age = new Date(ageInMillis);
return age.getYear();
}
但是因为getYear()被弃用了,我想知道是否有更好的方法来做到这一点?我甚至不确定这是否正常,因为我还没有进行单元测试。
#1 热门回答(160 赞)
查看Joda,它简化了日期/时间计算(Joda也是新标准Java日期/时间apis的基础,因此你将学习一个即将成为标准的API)。
编辑:Java 8 hassomething very similar,值得一试。
例如
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
这就是你想要的那么简单。 Java 8之前的东西(正如你所确定的那样)有点不直观。
#2 热门回答(122 赞)
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。所有早期版本都已经过了他们的支持生命。
#3 热门回答(38 赞)
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(...);
if (dob.after(now)) {
throw new IllegalArgumentException("Can't be born in the future");
}
int year1 = now.get(Calendar.YEAR);
int year2 = dob.get(Calendar.YEAR);
int age = year1 - year2;
int month1 = now.get(Calendar.MONTH);
int month2 = dob.get(Calendar.MONTH);
if (month2 > month1) {
age--;
} else if (month1 == month2) {
int day1 = now.get(Calendar.DAY_OF_MONTH);
int day2 = dob.get(Calendar.DAY_OF_MONTH);
if (day2 > day1) {
age--;
}
}
// age is now correct