views:

89

answers:

3

I'd like to write a simple function to say in hours :

How much time has passed since this has been created?

My attempts are futile.

-time = DateTime.now.hour - (self.created_at.hour)

Does anyone know how to do this in Ruby on Rails?

A: 

You are looking for the time_ago_in_words(from_time, include_seconds = false) function. Here are some examples from the docs:

time_ago_in_words(3.minutes.from_now)       # => 3 minutes
time_ago_in_words(Time.now - 15.hours)      # => 15 hours
time_ago_in_words(Time.now)                 # => less than a minute
from_time = Time.now - 3.days - 14.minutes - 25.seconds     # => 3 days
sosborn
I'm not looking for words. I'm looking on how to subtract a DateTime from another DateTime
Trip
In that case mckeed has the right answer.
sosborn
+1  A: 

Rails usually uses Time, not DateTime. Why don't you do Time.now - self.created_at? Then you can convert from seconds to hours by dividing by 3600.

mckeed
A: 

Got it!. First you have to make sure your data is in the same data it will be subtracted from whether its a Time or a DateTime. I chose time. Then you divide it by Ruby's built in time methods. This translates into how many days, but it can also be, 1.hour. etc.

(Time.now - self.created_at.to_time)/1.day
Trip