How to create method for age calculation method in android

前端 未结 7 1195
情话喂你
情话喂你 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 09:56

    None of the posted solutions worked for me. So, I worked my own logic and got this, which works 100% for me:

     Integer getAge(Integer year, Integer month, Integer 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(month == (today.get(Calendar.MONTH)+1) && day > today.get(Calendar.DAY_OF_MONTH)) {
             age--;
         }
    
         return age;
     }
    

提交回复
热议问题