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
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.