How do I calculate someone's age in Java?

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

    public int getAge(Date dateOfBirth) 
    {
        Calendar now = Calendar.getInstance();
        Calendar dob = Calendar.getInstance();
    
        dob.setTime(dateOfBirth);
    
        if (dob.after(now)) 
        {
            throw new IllegalArgumentException("Can't be born in the future");
        }
    
        int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
    
        if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) 
        {
            age--;
        }
    
        return age;
    }
    

提交回复
热议问题