Calculate age from BirthDate

后端 未结 17 1368
攒了一身酷
攒了一身酷 2021-02-07 08:33

I have DatePicker Dialog, When I select date at that time I want to calculate age it\'s working but when I select date of current year at that time it showing the -1 age instead

17条回答
  •  再見小時候
    2021-02-07 08:47

    This is the shortest I could get it to.

    static int calculateAge(Calendar birthDay){
           Calendar today = Calendar.getInstance();
    
           int age = today.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
    
           if (birthDay.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR)) {
                    age--;
            }
           return age;
    }
    

提交回复
热议问题