Calculate age from BirthDate

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

    java.time

    For the sage 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).

提交回复
热议问题