Forum: Ruby on Rails Time calculations - newbe attempts

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
D8a2f0ef1481beae5ecd0c37f4c0b1db?d=identicon&s=25 AaaaA A. (Guest)
on 2017-04-13 16:58
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 topic is locked and can not be replied to.