Netskin Logo

Calculate Age in Ruby on Rails

#ruby
by Thomas Rudolf on 01.09.2022

This is going to be a quick post. It was inspired by a task I was working on a few weeks ago, where the age of a user had to be displayed alongside their name. Sounds simple, right? But I quickly realized, that it’s not as simple as I thought. Rails usually has a convenience method for almost everything, and even Ruby’s core library ships with lots of useful methods for interacting with Date or DateTime objects, but there was no out-of-the-box way to calculate the age of somebody on a given day.

If we just calculate the days since the date of birth, we’d have to take the 30 vs 31 vs 28 days of months as well as leap years into account to get an exact result, so that would be pretty tiresome.

After a bit of playing around, I came up with this approach:

def age(date_of_birth)
  today = Date.today
  age = today.year - date_of_birth.year
  (today.strftime("%m%d").to_i >= date_of_birth.strftime("%m%d").to_i) ? age : age - 1
end

First, we calculate the difference of just the year parts of the birth date and today. Then, we do a simple Integer comparison of the month & day part of the dates, expressed in the format mmdd to evaluate if today is before or on/after the birthday. If today is on or after the birth date, the age is simply the calculated difference of the years from the first step, if not, that means the person’s birthday still lies ahead - so we have to subtract 1 from the year difference. By splitting the calculation up into those two steps, we do not have to worry about leap years and month lengths.

Maybe this comes in handy to you one day :)

Happy Coding!

❮ Ruby arrays cheatsheet
Default Button for HTML Forms with Multiple Buttons ❯
Netskin Logo