Fellow Stranger
Fellow Stranger

Reputation: 34103

Return minutes in DateTime subtraction

The following returns (5/12), a Rational object.

d = DateTime.current
d2 = d + 10.hours
d2 - d

How would I get the minute difference from the two points in time?

Upvotes: 3

Views: 1160

Answers (3)

Nermin
Nermin

Reputation: 6100

date_diff = date_2 - date_1
date_diff_array = Date.day_fraction_to_time(diff) # => [h, m, s, frac_s]

date_diff_array[0] # hours 
date_diff_array[1] # minutes 
date_diff_array[2] # seconds 

Upvotes: 1

pangpang
pangpang

Reputation: 8831

(d2 - d).class
=> Rational

Rational: A rational number can be represented as a paired integer number; a/b (b>0). Where a is numerator and b is denominator. Integer a equals rational a/1 mathematically.

d2 - d
=> (5/12)  #get the number of days

((d2 - d) * 24 * 60).to_i
=> 600    # get the number of minutes

Upvotes: 1

Max Williams
Max Williams

Reputation: 32955

DateTimes are all ultimately just a single number, float or int, under the hood, with the number representing seconds since epoch. When you do addition and subtraction it's doing the maths with these numbers, If it makes sense for the result to be a datetime it will usually return a datetime, but if it doesn't, it will just give you the number back.

When you subtract a time from another, the difference is a number of seconds. The Rational class is a way of holding the number, as an fraction rather than as a Float or Int.

Calling to_i or to_f will convert the number into an int or a float, depending on your requirements. You've then got a number of seconds, and you can convert this into a number of minutes by dividing it by 60.

Watch out for this gotcha: in ruby, if you divide an int by an int, it will round down the result to keep it an int. eg

90/60
=> 1

If you want a float back, 1.5 in this case, make sure at least one of the operands of the division is a float.

so, this should work:

d = DateTime.current
d2 = d + 10.hours
diff_minutes = (d2 - d)/60.0

Upvotes: 1

Related Questions