Calculate age from BirthDate

后端 未结 17 1585
攒了一身酷
攒了一身酷 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条回答
  •  萌比男神i
    2021-02-07 08:38

    private int getAge(String dobString){
    
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            date = sdf.parse(dobString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    
        if(date == null) return 0;
    
        Calendar dob = Calendar.getInstance();
        Calendar today = Calendar.getInstance();
    
        dob.setTime(date);
    
        int year = dob.get(Calendar.YEAR);
        int month = dob.get(Calendar.MONTH);
        int day = dob.get(Calendar.DAY_OF_MONTH);
    
        dob.set(year, month+1, day);
    
        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
    
        if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
            age--;
        }
    
    
    
        return age;
    }
    

提交回复
热议问题