Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of hours between two dates - Ruby

Say I want the difference between tomorrow and now (in hours).

What I've tried:

t = (DateTime.tomorrow - DateTime.now)
(t / 3600).to_i
=> 0

Why does it give 0?

What am I doing wrong?

like image 230
borjagvo Avatar asked Apr 21 '15 09:04

borjagvo


5 Answers

This is because DateTime.tomorrow does not have any time value. Here:

DateTime.tomorrow
# => Wed, 22 Apr 2015

If you go through official document for DateTime you can see there is no method tomorrow. Its basically Date#tomorrow.

You can use .to_time to get default localtime 00:00:00

DateTime.tomorrow.to_time
# => 2015-04-22 00:00:00 +0530

(DateTime.tomorrow.to_time - DateTime.now) / 1.hours
# => 9.008116581638655

To get exact hour difference between dates:

(DateTime.tomorrow.to_time - Date.today.to_time) / 1.hours 
# => 24.0
like image 172
shivam Avatar answered Nov 18 '22 09:11

shivam


Try this

t = (DateTime.tomorrow.to_time - Date.today.to_time)
t = (t / 3600).to_i
like image 40
Mahadeva Prasad Avatar answered Nov 18 '22 08:11

Mahadeva Prasad


It returns rational number. You can take days number if you'll use round method:

>> (DateTime.tomorrow - DateTime.now).round
1

Or if you want to take value in hours from now, use Time class:

>> (Date.tomorrow.to_time - Time.now) / 1.hour
11.119436663611111
like image 20
mico Avatar answered Nov 18 '22 07:11

mico


if you have two dates like

start_time = Time.new(2015,1, 22, 35, 0)
end_time = Time.new(2015,2, 22, 55, 0)

Try Time Difference gem for Ruby at https://rubygems.org/gems/time_difference

def timediff(start, end)
  TimeDifference.between(start, end).in_hours
end

and call it like:

timediff(start_time, end_time)

It will work. Cheers!

like image 1
Manish Shrivastava Avatar answered Nov 18 '22 07:11

Manish Shrivastava


There's DateTime#seconds_until_end_of_day:

seconds = DateTime.now.seconds_until_end_of_day
#=> 41133

seconds / 3600
#=> 11

distance_of_time_in_words(seconds)
=> "about 11 hours"
like image 1
Stefan Avatar answered Nov 18 '22 07:11

Stefan