How to Calculate Age in Elixir (Date.diff and Birthday Logic Examples)
Learn how to calculate age from date of birth in Elixir with Date.diff, birthday checks, and a compact helper for completed years.
How to Calculate Age in Elixir (Date.diff and Birthday Logic Examples)
If you only need a person's age in completed years, the core job is simple: subtract the birth year, then reduce by one if the birthday has not happened yet this year. In Elixir, Date already gives you the pieces you need.
Fast option: use an online age calculator
If you need an exact result in years, months, and days, or want to test your code against a known answer, start with a tool.
Open the age calculator and enter the date of birth plus any reference date.
Age in full years with Elixir
This helper returns the number of completed years as of a given date.
defmodule Age do
def years(%Date{} = dob, %Date{} = as_of \ Date.utc_today()) do
years = as_of.year - dob.year
had_birthday =
{as_of.month, as_of.day} >= {dob.month, dob.day}
if had_birthday, do: years, else: years - 1
end
end
Age.years(~D[1998-10-12])
Using Date.diff for a rough day check
Date.diff/2 is handy when you want to confirm the range between dates, but for age in years you should still keep the birthday check. Dividing days by 365 is only an approximation.
days = Date.diff(Date.utc_today(), ~D[1998-10-12])
Parse ISO dates safely
If the date of birth comes from a form or API, parse it first and handle invalid input explicitly.
case Date.from_iso8601("1998-10-12") do
{:ok, dob} -> Age.years(dob)
{:error, _} -> {:error, :invalid_date}
end
FAQ
What is the usual definition of age?
In most apps, age means completed years. Someone turns 30 on their birthday, not before.
How do I get years, months, and days?
You can build that logic manually, but month lengths and leap years make it easy to get wrong. A calculator is useful for validation.