Calculate age from BirthDate

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

    Here is a Kotlin extension of the Date class returning the age corresponding to a Date object

    val Date.age: Int
    get() {
        val calendar = Calendar.getInstance()
        calendar.time = Date(time - Date().time)
        return 1970 - (calendar.get(Calendar.YEAR) + 1)
    }
    

    It is compatible for all Android versions. If you wonder what '1970' is, that's the Unix Epoch. The timestamp is 0 on January 1, 1970.

提交回复
热议问题