I'd like to write a simple 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?
For adding or subtracting date, we use something called timedelta() function which can be found under datetime class. It is used to manipulate date, and we can perform an arithmetic operations on date like adding or subtract.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With