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(); }
Limitations:
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; } } }
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); } }
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!