borjagvo
borjagvo

Reputation: 2081

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?

Upvotes: 11

Views: 15263

Answers (5)

Stefan
Stefan

Reputation: 114188

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"

Upvotes: 1

Manish Shrivastava
Manish Shrivastava

Reputation: 32050

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!

Upvotes: 1

Mahadeva Prasad
Mahadeva Prasad

Reputation: 709

Try this

t = (DateTime.tomorrow.to_time - Date.today.to_time)
t = (t / 3600).to_i

Upvotes: 5

mico
mico

Reputation: 11

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

Upvotes: 1

shivam
shivam

Reputation: 16506

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

Upvotes: 26

Related Questions