如何计算某人的Java年龄? [英] How do I calculate someone's age in Java?
本文介绍了如何计算某人的Java年龄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Java方法中返回一个以年为单位的年龄。
我现在的是下面的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).
推荐答案
查看
编辑:Java 8有非常相似的并值得一试。
Java 8 has something very similar and is worth checking out.
例如
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
这是你想要的那么简单。当前的Java东西(正如你所确定的)有点不直观。
which is as simple as you could want. The current Java stuff is (as you've identified) somewhat unintuitive.
这篇关于如何计算某人的Java年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文