How do I calculate someone's age in Java?

前端 未结 28 2328
渐次进展
渐次进展 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:02

    The correct answer using JodaTime is:

    public int getAge() {
        Years years = Years.yearsBetween(new LocalDate(getBirthDate()), new LocalDate());
        return years.getYears();
    }
    

    You could even shorten it into one line if you like. I copied the idea from BrianAgnew's answer, but I believe this is more correct as you see from the comments there (and it answers the question exactly).

提交回复
热议问题