Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime subtraction in ruby 2?

I need to subtract two DateTime objects in order to find out the difference in hours between them.

I try to do the following:

a = DateTime.new(2015, 6, 20, 16)
b = DateTime.new(2015, 6, 21, 16)
puts a - b

I get (-1/1), the object of class Rational.

So, the question is, how do I find out what the difference betweent the two dates is? In hours or days, or whatever.

And what does this Rational mean/represent when I subtract DateTimes just like that?

BTW:

When I try to subtract DateTime's with the difference of 1 year, I get (366/1), so when I do (366/1).to_i, I get the number of days. But when I tried subtracting two DateTime's with the difference of 1 hour, it gave me -1, the number of hours. So, how do I also find out the meaning of the returned value (hours, days, years, seconds)?

like image 451
Denis Yakovenko Avatar asked Jun 20 '15 12:06

Denis Yakovenko


2 Answers

When you substract two datetimes, you'll get the difference in days, not hours.

You get a Rational type for the precision (some float numbers cannot be expressed exactly with computers)

To get a number of hours, multiply the result by 24, for minutes multiply by 24*60 etc...

a = DateTime.new(2015, 6, 20, 16)
b = DateTime.new(2015, 6, 21, 16)

(a - b).to_i 
# days
# => -1

((a - b)* 24).to_i  
# hours
# => -24
# ...

Here's a link to the official doc

like image 98
jazzytomato Avatar answered Nov 07 '22 15:11

jazzytomato


If you do subtraction on them as a Time object it will return the result in seconds and then you can multiply accordingly to get minutes/hours/days/whatever.

a = DateTime.new(2015, 6, 20, 16)
b = DateTime.new(2015, 6, 21, 16)
diff = b.to_time - a.to_time    # 86400
hours = diff / 60 / 60          # 24
like image 12
frostmatthew Avatar answered Nov 07 '22 16:11

frostmatthew