How do you subtract from a datetime?
I'd like to write a sim开发者_运维知识库ple function to say in hours:
How much time has passed since this has been created?
My attempts:
-time = DateTime.now.hour - (self.created_at.hour)
Does anyone know how to do this in Ruby on Rails?
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.
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
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
精彩评论