Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you subtract from a datetime?

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?

like image 245
Trip Avatar asked Jul 23 '10 00:07

Trip


People also ask

Can you subtract datetime objects?

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.


2 Answers

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.

like image 118
mckeed Avatar answered Oct 08 '22 23:10

mckeed


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
like image 37
Trip Avatar answered Oct 08 '22 23:10

Trip