I want to make a Person class in an android application. In that class I want to store the birthday of this person, and later calculate with this date (for example how old he is, or how many days left to his next birthday). I don't know how to do this, altough I tried several classes, such as Date (which is deprecated), and GregorianCalendar, which is not available below API level 28 (I use API level 21).
Asked
Active
Viewed 483 times
2 Answers
2
Use the ThreeTen Android Backport to bring java.time
to android pre API 26.
Then you can use a LocalDate
to represent the birthday without time zone information (as it is valid in all time zones.) See https://stackoverflow.com/a/39379431/4265739 for an overview of the time classes.
For calculating age with java.time
in kotlin you can use (shamelessly adapted from this)
val start = LocalDate.of(1996, 2, 29)
val end = LocalDate.of(2014, 2, 28) // use for age-calculation: LocalDate.now()
val years = ChronoUnit.YEARS.between(start, end)
println(years) // 17
For how to install follow the instructions in the github repo and see How to use ThreeTenABP in Android Project if you are running into problems.

leonardkraemer
- 6,573
- 1
- 31
- 54