Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate age from BirthDate [duplicate]

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

1 Answers

java.time

For the sake of completeness and being up-to-date concerning packages, here is the way using java.time (Java 8+).

Java

public int getAge(int year, int month, int dayOfMonth) {
    return Period.between(
                LocalDate.of(year, month, dayOfMonth),
                LocalDate.now()
            ).getYears();
}

Kotlin

fun getAge(year: Int, month: Int, dayOfMonth: Int): Int {
    return Period.between(
                LocalDate.of(year, month, dayOfMonth),
                LocalDate.now()
            ).years
}

Both snippets need the following imports from java.time:

import java.time.LocalDate;
import java.time.Period

It's not recommended to use java.util.Date and java.util.Calendar anymore except from situations where you have to involve considerably large amounts of legacy code.

See also Oracle Tutorial.

For projects supporting Java 6 or 7, this functionality is available via the ThreeTenBP,
while there is special version, the ThreeTenABP for API levels below 26 in Android.

UPDATE
There's API Desugaring now in Android, which makes (a subset of) java.time directly available (no backport library needed anymore) to API levels below 26 (not really down to version 1, but will do for most of the API levels that should be supported nowadays).

like image 126
deHaar Avatar answered Sep 07 '25 19:09

deHaar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!