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?
on 2006-12-23 11:22
on 2006-12-23 11:38
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.
on 2006-12-23 14:35
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!
on 2006-12-23 14:45
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)/(60*60*24)/365.2422).to_i end Cheers, JÃ¸rgen
on 2006-12-23 18:14
Aw, works perfect. Thanks!
on 2006-12-23 23:28
this will not work? def age (time) return (DateTime.now - time).years end
on 2006-12-24 01:23
Elad Meidar - Creopolis.com wrote: > this will not work? > > def age (time) > return (DateTime.now - time).years > end Nope. Can you?
on 2006-12-24 06:22
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
on 2006-12-24 10:20
Yes, for now this is the only unit based math I need. I'll definately remember those gems for future features though. Thanks!