Calculate age from BirthDate

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

    This is how I implement in my source code, I tested. Hope that it is useful :

    public static int getAge(String dateTime, String currentFormat) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(currentFormat);
    
        try {
            Date date = dateFormat.parse(dateTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
    
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
    
    
            Date currentDate = new Date();
            Calendar currentCalendar = Calendar.getInstance();
            currentCalendar.setTime(currentDate);
    
            int currentYear = currentCalendar.get(Calendar.YEAR);
            int currentMonth = currentCalendar.get(Calendar.MONTH);
            int currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH);
    
            int deltaYear = currentYear - year;
            int deltaMonth = currentMonth - month;
            int deltaDay = currentDay - day;
    
            if (deltaYear > 0) {
                if (deltaMonth < 0) {
                    deltaYear --;
                } else if (deltaDay < 0){
                    deltaYear --;
                }
    
                return deltaYear;
            }
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
    
        return 0;
    }
    

提交回复
热议问题