Mark
Mark

Reputation: 69930

Subtract dates in Ruby and get the difference in minutes

how do i subtract two different UTC dates in Ruby and then get the difference in minutes?

Thanks

Upvotes: 44

Views: 50534

Answers (4)

techdreams
techdreams

Reputation: 5585

Let's say you have two dates task_signed_in and task_signed_out for a simple @user object. We could do like this:

(@user.task_signed_out.to_datetime - @user.task_signed_in.to_datetime).to_i

This will give you result in days. Multiply by 24 you will get result in hours and again multiply by 60 you will result in minutes and so on.

This is the most up to date solution tested in ruby 2.3.x and above.

Upvotes: 0

user2295540
user2295540

Reputation: 477

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

start_time = Time.new(2013,1)
end_time = Time.new(2014,1)
TimeDifference.between(start_time, end_time).in_minutes

Upvotes: 23

Alex Korban
Alex Korban

Reputation: 15126

If you subtract two Date or DateTime objects, the result is a Rational representing the number of days between them. What you need is:

a = Date.new(2009, 10, 13) - Date.new(2009, 10, 11)
(a * 24 * 60).to_i   # 2880 minutes

or

a = DateTime.new(2009, 10, 13, 12, 0, 0) - DateTime.new(2009, 10, 11, 0, 0, 0)
(a * 24 * 60).to_i   # 3600 minutes

Upvotes: 63

Chubas
Chubas

Reputation: 18053

(time1 - time2) / 60

If the time objects are string, Time.parse(time) them first

Upvotes: 37

Related Questions