Time calculations - newbe attempts

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!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs