Kotlin with Copilot: Given a birthday date, calculate how old a person is, in years.
Video: Kotlin with Copilot: Given a birthday date, calculate how old a person is, in years. by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin: Calculate Age from Birthday Date
In Kotlin, you can easily calculate a person's age in years given their birthday date by using the standard library's date and time API. This example demonstrates how to work with LocalDate and Period classes to find the difference between the birthday and the current date.
Code
import java.time.LocalDate
import java.time.Period
fun calculateAge(birthday: LocalDate): Int {
val today = LocalDate.now()
// Calculate the period between birthday and today
val age = Period.between(birthday, today).years
return age
}
// Example usage:
fun main() {
val birthday = LocalDate.of(1990, 5, 15) // May 15, 1990
val age = calculateAge(birthday)
println("Age is $age years")
}
Key Points
- Use java.time.LocalDate to represent dates without time components in Kotlin.
- Period.between() calculates the difference between two LocalDate instances.
- The years property of Period gives the full years elapsed between dates.
- LocalDate.now() fetches the current date based on the system clock.