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

查看:26
本文介绍了我如何用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).

推荐答案

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计算某人的年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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