How do I calculate someone's age in Java?

前端 未结 28 3017
渐次进展
渐次进展 2020-11-22 02:20

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 ;-)):



        
28条回答
  •  清歌不尽
    2020-11-22 03:14

    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;
            }
        }
    }
    

    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);
        }
    }
    

    Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.

提交回复
热议问题