Age of person - ActiveSupport

I’ve got a datetime column in my database for a person’s age. How would
I be able to calculate the number of years they are from the DB date to
current time? I’ve looked at ActiveSupport and tried a few ways but
can’t figure it out. Anyone have any ideas on the best way to implement
this?

Hi Justin,

Where do you want to use this calculations?
if you want to use it in a view, you can use the
distance_of_time_in_words_to_now.

if you want to use it in a controller, well this is a problem i have
also… all the text helpers does not work with the an ActiveSupport
elements.

I tried the ‘time_ago_in_words’ helper method but it comes up as ‘over 4
years’ when what I need is the approximate number of years. Any idea on
how to get the method to display the exact number(integer) of years?

Thanks for the help!

Aw, works perfect. Thanks!

Justin Ko wrote:

I’ve got a datetime column in my database for a person’s age. How would
I be able to calculate the number of years they are from the DB date to
current time? I’ve looked at ActiveSupport and tried a few ways but
can’t figure it out. Anyone have any ideas on the best way to implement
this?

In my Rails app I do it like this:

def age
((Time.now - birthday)/(606024)/365.2422).to_i
end

Cheers,
Jørgen

Elad M. - Creopolis.com wrote:

this will not work?

def age (time)
return (DateTime.now - time).years
end

Nope. Can you?

this will not work?

def age (time)
return (DateTime.now - time).years
end

Justin Ko wrote:

Posted via http://www.ruby-forum.com/.
This is probably overkill if this is the only unit based math you want
to do but…

gem install ruby-units

require ‘ruby-units’
age = ‘years’.since(birthday) # where birthday is either a Time,
DateTime, or string of a date

if you install and require the ‘Chronic’ gem, you can pass all sorts of
funky stuff…

require ‘chronic’
‘days’.until ‘monday’ #=> 1.48601 days

_Kevin

Yes, for now this is the only unit based math I need. I’ll definately
remember those gems for future features though. Thanks!