How do I calculate someone's age in Java?

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

    String dateofbirth has the date of birth. and format is whatever (defined in the following line):

    org.joda.time.format.DateTimeFormatter formatter =  org.joda.time.format.DateTimeFormat.forPattern("mm/dd/yyyy");
    

    Here is how to format:

    org.joda.time.DateTime birthdateDate = formatter.parseDateTime(dateofbirth );
    org.joda.time.DateMidnight birthdate = new         org.joda.time.DateMidnight(birthdateDate.getYear(), birthdateDate.getMonthOfYear(), birthdateDate.getDayOfMonth() );
    org.joda.time.DateTime now = new org.joda.time.DateTime();
    org.joda.time.Years age = org.joda.time.Years.yearsBetween(birthdate, now);
    java.lang.String ageStr = java.lang.String.valueOf (age.getYears());
    

    Variable ageStr will have the years.

提交回复
热议问题