Time calculations - newbe attempts


#1

Hi, I’m new to Ruby, Rails and Ruby Forum.
I’m trying to build an app in Rails where a user can select hours and
minutes from 2 dropdowns and then get new time back.

I fetch hours and minutes as strings from form to db, like “05 am” hours
and “00” minutes. Then I convert them to an integer in minutes, like
18:30 = 1110 (time1). Then I need to subtract X minutes (time2) and get
new time (time3) in the 12:30 format. Basically, to subtract time2 from
time1 and get time3 (like 18:00-120 minutes = 16:00).

I was trying to do it with Time class, but didn’t find a way to convert
my minutes integer to time. I tried to use divmod to calculate new time
using integers:
<% @usertime = Usertime.last %>
<% t = (@usertime.hours.to_i * 60 + @usertime.minutes.to_i)

  • 600 %>
    <% hour, t = t.divmod(60) %>
    <%= “%02d:%02d” % [hour, t] %>

but for a range of hours that are less than time I want t0 subtract it
gives negative time, like 01:00 => -7:30 (should be 17:30).

Could you please give me the right direction to solve this?

Thank you!


#2

AaaaA AaaaA wrote in post #1185805:

new time (time3) in the 12:30 format. Basically, to subtract time2 from
time1 and get time3 (like 18:00-120 minutes = 16:00).

I was trying to do it with Time class, but didn’t find a way to convert
my minutes integer to time. I tried to use divmod to calculate new time

see Time api : http://ruby-doc.org/core-2.4.1/Time.html#method-i-2D :

time + numeric → time
Addition — Adds some number of seconds (possibly fractional) to time and
returns that value as a new Time object.t(int) : create a new time
object from epoch time

time - numeric → time
Difference — Returns a new Time object that represents the difference
between time and other_time, or subtracts the given number of seconds in
numeric from time.