How do I calculate someone's age in Java?

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

    public int getAge(String birthdate, String today){
        // birthdate = "1986-02-22"
        // today = "2014-09-16"
    
        // String class has a split method for splitting a string
        // split()
        // birth[0] = 1986 as string
        // birth[1] = 02 as string
        // birth[2] = 22 as string
        // now[0] = 2014 as string
        // now[1] = 09 as string
        // now[2] = 16 as string
        // **birth** and **now** arrays are automatically contains 3 elements 
        // split method here returns 3 elements because of yyyy-MM-dd value
        String birth[] = birthdate.split("-");
        String now[] = today.split("-");
        int age = 0;
    
        // let us convert string values into integer values
        // with the use of Integer.parseInt()
        int ybirth = Integer.parseInt(birth[0]);
        int mbirth = Integer.parseInt(birth[1]);
        int dbirth = Integer.parseInt(birth[2]);
    
        int ynow = Integer.parseInt(now[0]);
        int mnow = Integer.parseInt(now[1]);
        int dnow = Integer.parseInt(now[2]);
    
        if(ybirth < ynow){ // has age if birth year is lesser than current year
            age = ynow - ybirth; // let us get the interval of birth year and current year
            if(mbirth == mnow){ // when birth month comes, it's ok to have age = ynow - ybirth if
                if(dbirth > dnow) // birth day is coming. need to subtract 1 from age. not yet a bday
                    age--;
            }else if(mbirth > mnow){ age--; } // birth month is comming. need to subtract 1 from age            
        }
    
        return age;
    }
    

提交回复
热议问题