How do I calculate someone's age in Java?

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

    Try to copy this one in your code, then use the method to get the age.

    public static int getAge(Date birthday)
    {
        GregorianCalendar today = new GregorianCalendar();
        GregorianCalendar bday = new GregorianCalendar();
        GregorianCalendar bdayThisYear = new GregorianCalendar();
    
        bday.setTime(birthday);
        bdayThisYear.setTime(birthday);
        bdayThisYear.set(Calendar.YEAR, today.get(Calendar.YEAR));
    
        int age = today.get(Calendar.YEAR) - bday.get(Calendar.YEAR);
    
        if(today.getTimeInMillis() < bdayThisYear.getTimeInMillis())
            age--;
    
        return age;
    }
    

提交回复
热议问题