Calculating age in Rails
Today I had to calculate an age in Rails and I wanted to share the process and final outcome and see if anyone had a nicer way.
My first attempt was pretty naive;
Time.zone.now.year - date_of_birth.year
This does work to a certain extent as in it will give you the age, however it won’t be accurate as it won’t take into account month. So it would be incorrect in many cases.
After a quick Google I came across this approach;
now = Time.zone.now.to_date
now.year - date_of_birth.year - ((now.month > date_of_birth.month || (now.month == date_of_birth.month && now.day >= date_of_birth.day)) ? 0 : 1)
This works perfectly but looks pretty full on and I was shocked at how complicated this made it seem. This isn’t the Rails I know and love ❤️.
After some team discussion this is finally what we came up with;
((Time.zone.now - date_of_birth.to_time) / 1.year.seconds).floor
Much better! This is;
- Subtracting the DOB (converted to time) from now; which returns the difference in seconds.
- Divide the result by the amount of seconds in 1 year, which we can handily get in Rails using
1.year.seconds
. - Finally
floor
the result to make sure we always round down.
Hopefully this helps if anyone else is ever looking for a nice way to calculate age in Rails. If there is a nicer way, I would love to hear it.