Search code examples
rubydatestamp

Ruby Converting Datestamp to Years old in Ruby


Possible Duplicate:
How to calculate how many years passed since a given date in Ruby?

I am trying to convert a datestamp taken from the database into value indicating how many years old a person is. I am sure this easy, but I can't seem to figure it out.


Solution

  • Assuming the datestamp is being retrieved as a DateTime value:

    require 'date'
    
    birth_date = DateTime.parse('1970-01-01 1:35 AM')
    time_now = DateTime.now
    
    (time_now - birth_date).to_i / 365 # => 41
    (time_now - birth_date).to_f / 365 # => 41.38907504054664
    

    birth_date is a mock value for what you should be retrieving from your database. The first value is years, the second is fractional years.

    Alternately, you can do it this way:

    years = time_now.year - birth_date.year
    years -= 1 if (birth_date.month > time_now.month)
    years # => 41
    

    This adjusts in case the person hasn't had their birthday yet. For instance, tweaking the birthday:

    birth_date = DateTime.parse('1970-12-31 11:59 PM')
    years = time_now.year - birth_date.year
    years -= 1 if (birth_date.month > time_now.month)
    years # => 40