Calculate age from BirthDate

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

    Here is my solution in Kotlin:

    import java.time.LocalDateTime
    
    fun getAge(birthYear: Int, birthMonth: Int, birthDay: Int): Int {
        var age: Int = LocalDateTime.now().year - birthYear
        if (birthMonth > LocalDateTime.now().monthValue || birthMonth == LocalDateTime.now().monthValue && birthDay > LocalDateTime.now().dayOfMonth) { age-- }
        if (age < 0) { age = 0 }
        return age
    }
    

提交回复
热议问题