Back to Blog
2 min read

How to Calculate Age in Haskell (Data.Time and Birthday Logic Examples)

Learn how to calculate age from date of birth in Haskell using Data.Time, with a reliable birthday check for completed years.

How to Calculate Age in Haskell (Data.Time and Birthday Logic Examples)

In Haskell, age usually means the number of completed years. The reliable pattern is simple: subtract the birth year, then reduce by one if the birthday has not happened yet in the reference year.

Fast option: use an online age calculator

If you want a quick check, or you need an exact result in years, months, and days, verify the dates in a calculator first and then mirror the same rule in code.

Open the age calculator and enter the date of birth plus the reference date.

Haskell example with Data.Time

This helper returns completed years as of a given date.

import Data.Time

ageYears :: Day -> Day -> Integer
ageYears dob asOf =
  let (by, bm, bd) = toGregorian dob
      (ay, am, ad) = toGregorian asOf
      years = ay - by
      hadBirthday = (am, ad) >= (bm, bd)
  in if hadBirthday then years else years - 1

main :: IO ()
main = do
  let dob = fromGregorian 1998 10 12
  today <- utctDay getCurrentTime
  print (ageYears dob today)

Parsing from an ISO date string

If the input already looks like 1998-10-12, you can parse it directly before passing it to the helper.

import Data.Time.Format (defaultTimeLocale, parseTimeM)

parseDob :: String -> Maybe Day
parseDob = parseTimeM True defaultTimeLocale "%F"

maybeAge :: String -> Day -> Maybe Integer
maybeAge dobStr asOf = do
  dob <- parseDob dobStr
  pure (ageYears dob asOf)

FAQ

Why not divide days by 365.25?

That can work as a rough estimate, but real age should follow birthdays. A direct birthday check avoids the usual off-by-one problems.

How do I calculate exact age in years, months, and days?

That is a separate problem because month lengths vary. It helps to validate your result with a dedicated calculator before using it in app logic.

Related