Calculate Age in Java – 在Java中计算年龄

最后修改: 2018年 7月 5日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll see how to calculate age using Java 8, Java 7 and Joda-Time libraries.

在这个快速教程中,我们将看到如何使用Java 8、Java 7和Joda-Time库来计算年龄。

In all cases, we’ll take the birth date and current date as input and return the calculated age in years.

在所有情况下,我们将把出生日期和当前日期作为输入,并返回以年为单位的计算年龄。

2. Using Java 8

2.使用Java 8

Java 8 introduced a new Date-Time API for working with dates and times, largely based off of the Joda-Time library.

Java 8 引入了新的日期-时间 API,用于处理日期和时间,主要基于 Joda-Time 库。

In Java 8, we can use java.time.LocalDate for our birth date and current date, and then use Period to calculate their difference in years:

在Java 8中,我们可以使用java.time.LocalDate来表示我们的出生日期和当前日期,然后使用Period来计算它们的年差。

public int calculateAge(
  LocalDate birthDate,
  LocalDate currentDate) {
    // validate inputs ...
    return Period.between(birthDate, currentDate).getYears();
}

LocalDate is helpful here because represents just a date, compared to Java’s Date class, which represents both a date and a time. LocalDate.now() can give us the current date.

LocalDate在这里很有帮助,因为它只代表一个日期,相比之下,Java的Date类既代表一个日期,也代表一个时间。LocalDate.now()可以给我们提供当前日期。

And Period is helpful when we need to think about time periods in years, months and days.

Period在我们需要考虑以年、月、日为单位的时间段时是有帮助的。

If we wanted to get a more exact age, say in seconds, then we’d want to take a look at LocalDateTime and Duration, respectively (and maybe return a long instead).

如果我们想得到一个更精确的年龄,比如说以秒为单位,那么我们就应该分别看看LocalDateTimeDuration(也许可以返回一个long代替)。

3. Using Joda-Time

3.使用Joda-Time

If Java 8 isn’t an option, we can still get the same kind of result from Joda-Time, a de-facto standard for date-time operations in the pre-Java 8 world.

如果Java 8不是一个选项,我们仍然可以从Joda-Time获得同样的结果,这是在Java 8之前的世界中用于日期-时间操作的事实标准。

We need to add the Joda-Time dependency to our pom:

我们需要将Joda-Time依赖项添加到我们的pom中。

<dependency>
  <groupId>joda-time</groupId>
  <artifactId>joda-time</artifactId>
  <version>2.10</version>
</dependency>

And then we can write a similar method to calculate age, this time using LocalDate and Years from Joda-Time:

然后我们可以写一个类似的方法来计算年龄,这次使用LocalDateYears来自Joda-Time

public int calculateAgeWithJodaTime(
  org.joda.time.LocalDate birthDate,
  org.joda.time.LocalDate currentDate) {
    // validate inputs ...
    Years age = Years.yearsBetween(birthDate, currentDate);
    return age.getYears();   
}

4. Using Java 7

4.使用Java 7

Without a dedicated API in Java 7, we are left to roll our own, and so there are quite a few approaches.

在Java 7中没有专门的API,我们只能自己动手了,所以有不少方法。

As one example, we can use java.util.Date:

作为一个例子,我们可以使用java.util.Date

public int calculateAgeWithJava7(
  Date birthDate, 
  Date currentDate) {            
    // validate inputs ...                                                                               
    DateFormat formatter = new SimpleDateFormat("yyyyMMdd");                           
    int d1 = Integer.parseInt(formatter.format(birthDate));                            
    int d2 = Integer.parseInt(formatter.format(currentDate));                          
    int age = (d2 - d1) / 10000;                                                       
    return age;                                                                        
}

Here, we convert the given birthDate and currentDate objects into integers and find the difference between them, and so long as we aren’t still on Java 7 in 8000 years, this approach should work until then.

在这里,我们将给定的birthDatecurrentDate对象转换为整数,并找出它们之间的差异,只要我们不是在8000年后还在使用Java 7,这种方法在那之前应该是可行的。

5. Conclusion

5.结论

In this article, we showed out how to calculate age easily using Java 8, Java 7 and Joda-Time libraries.

在这篇文章中,我们展示了如何使用Java 8、Java 7和Joda-Time库来轻松计算年龄。

To learn more about Java 8’s data-time support check out our Java 8 date-time intro.

要了解有关 Java 8 的数据时间支持的更多信息,请查看我们的 Java 8 日期时间介绍

And as always, the complete code for these snippets can be found over on GitHub.

和往常一样,这些片段的完整代码可以在GitHub上找到