0

I am calculating the age of a kid based on Birthday.

This is the code as it is. It works. I strongly suspect this is not a good way of doing this. Currently, the code in is the view and I do plan to move it to a helper eventually. That is not relevant.

TLDR; User suspects the code below is brittle and will lead to future issues (such as leap year birthdays?). Please advise.

<%= ((Date.today - children.child_birthday).to_i)/365 %>
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Puchembo
  • 5
  • 5

1 Answers1

-1

This should handle the leap year case, in your controller add this helper function:

Controller:

def get_age
  dob = children.child_birthday
  now = Time.now.utc.to_date
  now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end

helper_method :get_age

And then you can display the children's birthday in your View:

<%= get_age %>
ifma
  • 3,673
  • 4
  • 26
  • 38