Calculate age from BirthDate

2020-06-03 01:25发布

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 of 0 then how can solve this? Please help me to solve it. My code is below:

public int getAge(int year, int month, int day) {

        GregorianCalendar cal = new GregorianCalendar();
        int y, m, d, noofyears;

        y = cal.get(Calendar.YEAR);// current year ,
        m = cal.get(Calendar.MONTH);// current month
        d = cal.get(Calendar.DAY_OF_MONTH);// current day
        cal.set(year, month, day);// here ur date
        noofyears = (int) (y - cal.get(Calendar.YEAR));
        LOGD("Age......", String.valueOf(noofyears));

        if ((m < cal.get(Calendar.MONTH)) || ((m == cal.get(Calendar.MONTH)) && (d < cal.get(Calendar.DAY_OF_MONTH)))) {
            --noofyears;
        }
        LOGD("Age......", String.valueOf(noofyears));
        if (noofyears != 0) {
            ageCount = noofyears;
        } else {
            ageCount = 0;
        }
        if (noofyears < 0)
            throw new IllegalArgumentException("age < 0");
        return noofyears;
    }

15条回答
何必那么认真
2楼-- · 2020-06-03 01:56
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)<today.get(Calendar.DAY_OF_MONTH))
                    {
                        intMonth++;
                        intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
                    }else {
                        temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
                        intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
                    }


                }


            }

        } else if ((iYear != today.get(Calendar.YEAR)) && (iYear != birth.get(Calendar.YEAR))) {



            for (int iMonth = 0; iMonth < 12; iMonth++) {
                temp.set(iYear, iMonth, 1);
                totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
                intMonth++;
            }


        } else if (((iYear) == birth.get(Calendar.YEAR))) {

            for (int iMonth = birth.get(Calendar.MONTH); iMonth < 12; iMonth++) {
                temp.set(iYear, iMonth, 1);
                if ((iMonth == birth.get(Calendar.MONTH))) {

                    totalDays += (birth.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH));

                } else {
                    intMonth++;
                    totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
                }
            }


        } else if (iYear == today.get(Calendar.YEAR)) {
            for (int iMonth = 0; iMonth <= today.get(Calendar.MONTH); iMonth++) {

                temp.set(iYear, iMonth, 1);
                if ((iMonth == today.get(Calendar.MONTH))) {

                    totalDays += today.get(Calendar.DAY_OF_MONTH);

                    if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
                    {
                        intMonth++;
                        intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
                    }else {
                        temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
                        intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
                    }

                } else {
                    intMonth++;
                    totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
                }
            }
        }
    }

    int  ageYear=intMonth/12;
    int  ageMonth=intMonth%12;
    int ageDays=intDays;
    //TODO if you want age in YEAR:MONTH:DAY REMOVE COMMENTS
   //TODO  return ageYear+":"+ageMonth+":"+ageDays;  
    return ""+totalDays;//todo TOTAL AGE IN DAYS

}
查看更多
该账号已被封号
3楼-- · 2020-06-03 01:59
public String getAge(int year, int month, int day) {
        Calendar dob = Calendar.getInstance();
        Calendar today = Calendar.getInstance();

        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--;
        }

        Integer ageInt = new Integer(age);
        String ageS = ageInt.toString();

        return ageS;
    }
查看更多
Juvenile、少年°
4楼-- · 2020-06-03 02:02
public int getAge(int year, int month, int day) {
    final Calendar birthDay = Calendar.getInstance();
    birthDay.set(year, month, day);
    final Calendar current = Calendar.getInstance();
    if (current.getTimeInMillis() < birthDay.getTimeInMillis())
        throw new IllegalArgumentException("age < 0");
    int age = current.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
    if (birthDay.get(Calendar.MONTH) > current.get(Calendar.MONTH) ||
            (birthDay.get(Calendar.MONTH) == current.get(Calendar.MONTH) &&
                    birthDay.get(Calendar.DATE) > current.get(Calendar.DATE)))
        age--;
    return age;
}
查看更多
▲ chillily
5楼-- · 2020-06-03 02:03

Considered Year as 365 days & Month as 30 Days

public static String getAge(long birthdateMillis){

        long millisFromBirthday = System.currentTimeMillis()-birthdateMillis;

        int totalSeconds = (int) (millisFromBirthday/1000);

        long totalSecondsInCalendarYear = 3600*24*365;

        int years = (int) (totalSeconds / totalSecondsInCalendarYear);

        int month = (int) ((totalSeconds % totalSecondsInCalendarYear)/(3600*24*30));

        String age = "";

        if (years>0){
            age = String.format("%d Years", years);
        }

        if (month>0){
            age = age +" " +String.format("%d Month", month);
        }

        return age;

    }

Output will be like, xx Years xx Month

查看更多
混吃等死
6楼-- · 2020-06-03 02:05
public static String calculateAge(String strDate) {

    int years = 0;
    int months = 0;
    int days = 0;

    try {
        long timeInMillis = Long.parseLong(strDate);
        Date birthDate = new Date(timeInMillis);


        //create calendar object for birth day
        Calendar birthDay = Calendar.getInstance();
        birthDay.setTimeInMillis(birthDate.getTime());
        //create calendar object for current day
        long currentTime = System.currentTimeMillis();
        Calendar now = Calendar.getInstance();
        now.setTimeInMillis(currentTime);
        //Get difference between years
        years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
        int currMonth = now.get(Calendar.MONTH) + 1;
        int birthMonth = birthDay.get(Calendar.MONTH) + 1;

        //Get difference between months
        months = currMonth - birthMonth;


        //if month difference is in negative then reduce years by one and calculate the number of months.
        if (months < 0) {
            years--;
            months = 12 - birthMonth + currMonth;
            if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
                months--;
        } else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
            years--;
            months = 11;
        }
        //Calculate the days
        if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
            days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
        else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
            int today = now.get(Calendar.DAY_OF_MONTH);
            now.add(Calendar.MONTH, -1);
            days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
        } else {
            days = 0;
            if (months == 12) {
                years++;
                months = 0;
            }
        }
        //adarsh
        if (currMonth > birthMonth) {
            if (birthDay.get(Calendar.DATE) > now.get(Calendar.DATE)) {
                months = months - 1;
            }
        }//---------------------------------

    } catch (Exception e) {
        e.printStackTrace();
    }
    //Create new Age object
    return years + " Y " + months + " M " + days + " days";
}
查看更多
老娘就宠你
7楼-- · 2020-06-03 02:05

This is the shortest I could get it to.

static int calculateAge(Calendar birthDay){
       Calendar today = Calendar.getInstance();

       int age = today.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);

       if (birthDay.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR)) {
                age--;
        }
       return age;
}
查看更多
登录 后发表回答