如何计算某人的Java年龄? [英] How do I calculate someone's age in Java?

查看:421
本文介绍了如何计算某人的Java年龄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以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).

推荐答案

一个href =http://joda-time.sourceforge.net/ =noreferrer> Joda ,这简化了日期/时间计算(Joda也是新的标准Java日期/时间apis的基础,所以你将会学习一个即将到来的API)。

Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).

编辑:Java 8已经类似,值得一试。

Java 8 has something very similar and is worth checking out.

eg

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆