Mountain View


Find age in java

Posted On : 22-Sep-2018 [113]



public int ageCalculate( Date dob){
        //System.out.println("Input Date --- > "+ inputDate);
        int outputAge = 0;
        try {
            Calendar today=Calendar.getInstance();
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            String inputDate = sdf.format(dob);
            Date dateOfBirth = sdf.parse(inputDate);
            System.out.println("\n calculateAge dateOfBirth "+dateOfBirth+"\n");
            cal.setTime(dateOfBirth);
            today.setTime(new Date());
            int years=0;
            int months=0;
            int days=0;
            if(today.get(Calendar.DAY_OF_MONTH)<cal.get(Calendar.DAY_OF_MONTH)){
                int noOfDaysInCurrentMonth=today.getActualMaximum(today.get(Calendar.MONTH));
                int noOfDaysInDOBmonth=cal.get(Calendar.DAY_OF_MONTH);
                days=(noOfDaysInCurrentMonth+today.get(Calendar.DAY_OF_MONTH))-noOfDaysInDOBmonth;
                //today.set(Calendar.MONTH,today.get(Calendar.MONTH)-1);
                if(today.get(Calendar.MONTH)<=cal.get(Calendar.MONTH)){
                    years=today.get(Calendar.YEAR)-1;
                    months=today.get(Calendar.MONTH)+12;
                    int dobYears=years-cal.get(Calendar.YEAR);
                    int dobMonths=months-cal.get(Calendar.MONTH);
                    outputAge = dobYears;
                    
                }else{
                    int dobYears = today.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
                    int dobMonths=today.get(Calendar.MONTH) - cal.get(Calendar.MONTH);
                    outputAge = dobYears;
                }
                
            }else{
                days=today.get(Calendar.DAY_OF_MONTH)-cal.get(Calendar.DAY_OF_MONTH);
                if(today.get(Calendar.MONTH)<cal.get(Calendar.MONTH)){
                    years=today.get(Calendar.YEAR)-1;
                    months=today.get(Calendar.MONTH)+12;
                    int dobYears=years-cal.get(Calendar.YEAR);
                    int dobMonths=months-cal.get(Calendar.MONTH);
                    outputAge = dobYears;
                }else{
                    int dobYears = today.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
                    int dobMonths=today.get(Calendar.MONTH) - cal.get(Calendar.MONTH);
                    outputAge = dobYears;
                }
            }
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        if(outputAge>0){
            System.out.println("outputAge --> "+outputAge);
        }
        return outputAge;
    }




Related Articles
Recent Articles
Most Viewed Articles