I wrote a little helper that calulates someone’s age based on his/her
date of birth.
def age(dob)
diff = Date.today - dob
age = (diff / 365.25).floor
age.to_s
end
It works fine, but it’s not completely accurate as it just takes the
average days in a year. It should be able to calculate this more
accurately, right? I can’t work it out though…
I wrote a little helper that calulates someone’s age based on his/her
date of birth.
def age(dob)
diff = Date.today - dob
age = (diff / 365.25).floor
age.to_s
end
It works fine, but it’s not completely accurate as it just takes the
average days in a year. It should be able to calculate this more
accurately, right? I can’t work it out though…
Jeroen
Give this a try Jeroen:
def get_age(dob)
return nil unless dob
now = Time.now
now.year - dob.year - (dob.to_time.change(:year => now.year) > now ? 1
: 0)
end
Here’s one that’s not optimized in any way, but it is accurate:
def age(dob)
unless dob.nil?
a = Date.today.year - dob.year
b = Date.new(Date.today.year, dob.month, dob.day)
a = a-1 if b > Date.today
return a
end
nil
end
def age(dob)
unless dob.nil?
years = Date.today.year - dob.year
if Date.today.month < dob.month
years = years + 1
end
if (Date.today.month == dob.month and
Date.today.day < dob.day)
years = years - 1
end
return years
end
nil
end
Frank
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.