Back to Blog
2 min read

How to Calculate Age in Ruby (Date and Birthday Logic Examples)

Learn how to calculate age from date of birth in Ruby with Date, a birthday check, and a compact helper you can reuse in Rails or plain Ruby.

How to Calculate Age in Ruby (Date and Birthday Logic Examples)

Age calculation in Ruby is straightforward if you define age as completed years. The main rule is simple: subtract birth year, then subtract one more year if the birthday has not happened yet.

Fast option: use an online age calculator

If you need an exact breakdown in years, months, and days, or you want to double-check a result for a past or future date, use a calculator first.

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

Age in full years with Ruby Date

This version works well in plain Ruby and in Rails apps that already use Date.

require 'date'

def age_years(dob, as_of = Date.today)
  years = as_of.year - dob.year
  birthday_passed = (as_of.month > dob.month) ||
                    (as_of.month == dob.month && as_of.day >= dob.day)
  birthday_passed ? years : years - 1
end

age_years(Date.new(1998, 10, 12))

Parsing a date string

If the date comes from a form or CSV, parse it once and reuse the same helper.

dob = Date.parse('1998-10-12')
age_years(dob)

Rails note

In Rails, prefer converting to Date before comparing. That avoids unnecessary time-of-day issues when the original value is a Time or DateTime.

dob = user.date_of_birth.to_date
age = age_years(dob, Date.current)

FAQ

What is the usual definition of age?

In most apps, age means completed years. Someone turns 18 on their 18th birthday, not earlier in the year.

What about leap day birthdays?

Rules vary by app or jurisdiction. If you need a legal or business-specific rule for Feb 29 birthdays, keep that rule explicit in your code and tests.

Related