Calculate age from BirthDate

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

    String getAgeInOther(int year, int month, int day) {
        Calendar today = Calendar.getInstance();
        Calendar birth = Calendar.getInstance();
        birth.set(year, month, day);
        Calendar temp = Calendar.getInstance();
        temp.set(year, month, day);
        int totalDays = 0;
    
        int intMonth=0,intDays=0;
    
        for (int iYear = birth.get(Calendar.YEAR); iYear <= today.get(Calendar.YEAR); iYear++) {
            if (iYear == today.get(Calendar.YEAR) && iYear == birth.get(Calendar.YEAR)) {
    
                for (int iMonth = birth.get(Calendar.MONTH); iMonth <= today.get(Calendar.MONTH); iMonth++) {
                    temp.set(iYear, iMonth, 1);
                    if ((iMonth == today.get(Calendar.MONTH)) && (iMonth == birth.get(Calendar.MONTH))) {
    
                        totalDays += today.get(Calendar.DAY_OF_MONTH) - birth.get(Calendar.DAY_OF_MONTH);
    
                    } else if ((iMonth != today.get(Calendar.MONTH)) && (iMonth != birth.get(Calendar.MONTH))) {
    
                        totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
                        intMonth++;
    
                    }else  if ((iMonth == birth.get(Calendar.MONTH))) {
    
                        totalDays +=( birth.getActualMaximum(Calendar.DAY_OF_MONTH)- birth.get(Calendar.DAY_OF_MONTH));
    
                    } else  if ((iMonth == today.get(Calendar.MONTH))){
    
                        totalDays += today.get(Calendar.DAY_OF_MONTH);
    
    
    
                        if (birth.get(Calendar.DAY_OF_MONTH)

提交回复
热议问题