How to create method for age calculation method in android

前端 未结 7 1184
情话喂你
情话喂你 2020-12-14 09:50

I want to write a method to calculate the age from the birth date, is the logic correct and how to write it in android Java:

public int calculateAge(String b         


        
相关标签:
7条回答
  • 2020-12-14 10:12

    Here is my solution to the problem:

    /**
     * Method to extract the user's age from the entered Date of Birth.
     * 
     * @param DoB String The user's date of birth.
     * 
     * @return ageS String The user's age in years based on the supplied DoB.
     */
    private String getAge(int year, int month, int day){
        Calendar dob = Calendar.getInstance();
        Calendar today = Calendar.getInstance();
    
        dob.set(year, month, day); 
    
        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
    
        if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
            age--; 
        }
    
        Integer ageInt = new Integer(age);
        String ageS = ageInt.toString();
    
        return ageS;  
    }
    

    I used a DatePicker to get the input values required here. This method, together with the date picker, is specifically to get the user's DoB and calculate their age. A slight modification can be made to allow for String input(s) of the user's DoB, depending upon your specific implementation. The return type of String is for updating a TextView, a slight mod can be made to allow for type int output also.

    0 讨论(0)
提交回复
热议问题