Calculate age from BirthDate

后端 未结 17 1363
攒了一身酷
攒了一身酷 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 09:00

          private void calculateAge() {
        age.calcualteYear();
        age.calcualteMonth();
        age.calcualteDay();
        age.calculateMonths();
        age.calTotalWeeks();
        age.calTotalHours();
        age.calTotalMins();
        age.calTotalSecs();
        age.calTotalMilsecs();
        // Toast.makeText(getContext(), "click the resulted button"+age.getResult() , Toast.LENGTH_SHORT).show();
        result.setText("AGE (DD/MM/YY) :" + age.getResult());
    }
    

    after that create one class

     public class AgeCalculation {
    private int startYear;
    private int startMonth;
    private int startDay;
    private int endYear;
    private int endMonth;
    private int endDay;
    private int resYear;
    private int resMonth;
    private int resDay;
    private Calendar start;
    private Calendar end;
    public String getCurrentDate()
    {
          end=Calendar.getInstance();
          endYear=end.get(Calendar.YEAR);
          endMonth=end.get(Calendar.MONTH);
          endMonth++;
          endDay=end.get(Calendar.DAY_OF_MONTH);
          return endDay+":"+endMonth+":"+endYear;
    }
    public void setDateOfBirth(int sYear, int sMonth, int sDay)
    {
     startYear=sYear;
     startMonth=sMonth;
     startDay=sDay;
    
    }
    public void calcualteYear()
    {
        resYear=endYear-startYear/(365);
    
    }
    
    public void calcualteMonth()
    {
        if(endMonth>=startMonth)
        {
             resMonth= endMonth-startMonth;
        }
        else
        {
            resMonth=endMonth-startMonth;
            resMonth=12+resMonth;
            resYear--;
        }
    
    }
    public void  calcualteDay()
    {
    
        if(endDay>=startDay)
        {
             resDay= endDay-startDay;
        }
        else
        {
            resDay=endDay-startDay;
            resDay=30+resDay;
            if(resMonth==0)
            {
                resMonth=11;
                resYear--;
            }
            else
            {
                resMonth--;
            }
    
        }
    }
    
    public String getResult()
    {
        return resDay+":"+resMonth+":"+resYear;
    }
    

提交回复
热议问题