How do I calculate someone's age in Java?

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

    Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).

    EDIT: Java 8 has something very similar and is worth checking out.

    e.g.

    LocalDate birthdate = new LocalDate (1970, 1, 20);
    LocalDate now = new LocalDate();
    Years age = Years.yearsBetween(birthdate, now);
    

    which is as simple as you could want. The pre-Java 8 stuff is (as you've identified) somewhat unintuitive.

提交回复
热议问题