How to Calculate Age in Scala (java.time and Period Examples)
Learn how to calculate age from date of birth in Scala with java.time.LocalDate and Period. Includes years-only logic, exact age components, and common edge cases.
If you need to calculate age in Scala, the simplest approach is to use Java's modern date API. In practice, that means comparing a birth date and a reference date with Period.between.
Quick option: verify the result first
If you want to double-check your logic or compare years, months, and days, use the age calculator and test your Scala output against it.
Age in completed years
This is the usual definition of age: full years completed as of today or another chosen date.
import java.time.LocalDate
import java.time.Period
object AgeExample {
def ageInYears(dob: LocalDate, asOf: LocalDate = LocalDate.now()): Int =
Period.between(dob, asOf).getYears
}This works well because Period.between respects whether the birthday has already happened this year.
Exact age in years, months, and days
If you need a more detailed result, keep the full Period instead of only the years.
import java.time.LocalDate
import java.time.Period
object ExactAgeExample {
def exactAge(dob: LocalDate, asOf: LocalDate = LocalDate.now()): Period =
Period.between(dob, asOf)
}You can then read getYears, getMonths, and getDays separately. If you want the non-code version too, see how to calculate your age precisely.
Parsing a birth date string
If the birth date comes from a form, parse it into LocalDate before doing the age calculation.
import java.time.LocalDate
val dob = LocalDate.parse("1998-10-12")
val age = Period.between(dob, LocalDate.now()).getYearsCommon mistakes
Subtracting years manually can be wrong if the birthday has not happened yet.
Ignoring the reference date can cause test failures and inconsistent results.
Mixing legacy date classes makes the code harder to reason about than using
java.time.
Related
FAQ
What is the best way to calculate age in Scala?
Use LocalDate and Period.between. It is clearer and safer than manual year subtraction.
Can Scala calculate exact age, not just years?
Yes. Keep the full Period and read the years, months, and days separately.