0

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

L.Z.
  • 11
  • 1

2 Answers2

2

Use the ThreeTen Android Backport to bring java.timeto 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
0

Indeed Java's Date class is awful in various ways; steer clear of it. If you can't use the good new Java 8 stuff like GregorianCalendar, the Joda-Time library is an excellent replacement.

Thomas
  • 174,939
  • 50
  • 355
  • 478