How to display ages instead of dates of birth, in Ruby on Rails? [duplicate]
Possible Duplicate:
Get person's age in Ruby
I am very new to Ruby on Rails, and I have just created a small program to store people, using their names, dates of birth (dob), genders, etc. However, when I query the people from the database using @persons = Persons.find(:all)
, and I try to list开发者_Python百科 them, I'd love to display their age, that is, today - persons.dob, rather than their date of birth proper.
today = Date.today
d = Date.new(today.year, dob.month, dob.day)
age = d.year - dob.year - (d > today ? 1 : 0)
def age(dob)
today = Date.today
age = today.year - dob.year
age -= 1 if dob.strftime("%m%d").to_i > today.strftime("%m%d").to_i
age
end
dob = Date.new(1976, 4, 10)
age(dob)
#=> 35
dob = Date.new(1976, 5, 10)
age(dob)
#=> 34
Apologies in advance...I'm still learning Ruby:
require 'date'
dob = Date.new(1976, 7, 4)
now = Date.today
age = ((now - dob) / 365.25).to_i
I'm guessing there's a better way...?
Rails has a couple of Date-Helpers, among them distance_of_time_in_words: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words.
As far as I remember it adds an "about x years", so it might be not useful in your particular situation unless you take a look at the source and adapt it.
Otherwise you can calculate with years directly calling Date.today.year (or dob.year).
This code seems to work for me with a few test ages
age = ((Date.today - dob).to_i / 365.25).ceil
where you define dob as the date object.
精彩评论