Calculate age from BirthDate

后端 未结 17 1349
攒了一身酷
攒了一身酷 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:55

    public static int getPerfectAgeInYears(int year, int month, int date) {
    
        Calendar dobCalendar = Calendar.getInstance();
        
        dobCalendar.set(Calendar.YEAR, year);
        dobCalendar.set(Calendar.MONTH, month);
        dobCalendar.set(Calendar.DATE, date);
    
        int ageInteger = 0;
    
        Calendar today = Calendar.getInstance();
    
        ageInteger = today.get(Calendar.YEAR) - dobCalendar.get(Calendar.YEAR);
    
        if (today.get(Calendar.MONTH) == dobCalendar.get(Calendar.MONTH)) {
    
            if (today.get(Calendar.DAY_OF_MONTH) < dobCalendar.get(Calendar.DAY_OF_MONTH)) {
    
                ageInteger = ageInteger - 1;
            }
    
        } else if (today.get(Calendar.MONTH) < dobCalendar.get(Calendar.MONTH)) {
    
            ageInteger = ageInteger - 1;
    
        }
    
        return ageInteger;
    }
    

    Consider Today's Date - 30th August 2020

    If Birthdate - 29th July 1993, the output - 27

    If Birthdate - 29th August 1993, the output - 27

    If Birthdate - 30th August 1993, the output - 27

    If Birthdate - 31st August 1993, the output - 26

    If Birthdate - 31st September 1993, the output - 26

提交回复
热议问题