How to Calculate Age in Kotlin (LocalDate and Period Examples)
Learn how to calculate age from date of birth in Kotlin with java.time LocalDate and Period, plus a clean function you can reuse in Android or backend apps.
How to Calculate Age in Kotlin (LocalDate and Period Examples)
Calculating age sounds easy until you hit birthdays that have not happened yet this year, leap years, and mixed date formats. In Kotlin, the safest approach is usually to rely on java.time.
Fast option: use an online age calculator
If you need an exact answer in years, months, and days, or you want a quick check for test cases, use a tool first and then mirror the logic in code.
Open the age calculator and enter the date of birth plus the reference date.
Calculate age with LocalDate and Period
This is the cleanest Kotlin solution for most apps.
import java.time.LocalDate
import java.time.Period
fun ageYears(dateOfBirth: LocalDate, asOf: LocalDate = LocalDate.now()): Int {
return Period.between(dateOfBirth, asOf).years
}
val years = ageYears(LocalDate.parse("1998-10-12"))
Why this works well
Period.between() understands calendar dates, so you avoid manual month and day comparisons. That makes it safer than subtracting years directly.
Parse a string safely
If your input is a string, parse it into LocalDate first.
import java.time.LocalDate
val dob = LocalDate.parse("1998-10-12")
val age = ageYears(dob)
Custom format example
If the input is not ISO format, add a formatter.
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val dob = LocalDate.parse("12/10/1998", formatter)
val age = ageYears(dob)
FAQ
Should I use LocalDate or LocalDateTime?
Use LocalDate for age based on birthdays. Age is usually a calendar concept, not a timestamp concept.
What about leap day birthdays?
LocalDate and Period handle calendar rules correctly, which is another reason to prefer them over manual math.
How do I get years, months, and days?
Use the full Period instead of just .years.
val diff = Period.between(dob, LocalDate.now())
println("${diff.years} years, ${diff.months} months, ${diff.days} days")