Home > Java > javaTutorial > How Can I Reliably Calculate Age in Years Using Java?

How Can I Reliably Calculate Age in Years Using Java?

DDD
Release: 2024-12-18 11:16:11
Original
291 people have browsed it

How Can I Reliably Calculate Age in Years Using Java?

Java Method for Calculating Age

Problem:

Develop a Java method that returns an age in years as an integer. The method takes a Date object representing the birth date.

Current Implementation:

public int getAge() {
    long ageInMillis = new Date().getTime() - getBirthDate().getTime();

    Date age = new Date(ageInMillis);

    return age.getYear();
}
Copy after login

Limitations:

  • getYear() method is deprecated.
  • The accuracy of the current method is questionable without unit tests.

Improved Solution with JDK 8:

JDK 8 introduces a refined solution using the LocalDate class:

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;
        }
    }
}
Copy after login

JUnit Test:

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);
    }
}
Copy after login

Recommendation:

Upgrade to JDK 8 for an improved and reliable solution for calculating age.

The above is the detailed content of How Can I Reliably Calculate Age in Years Using Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template