I'm writing a function that adds minutes to a time string - without using any libraries for Time. The function takes two arguments -
- The first, a "time" ([H]H:MM AM|PM) String, in the format of something like
12:00 AM
or3:30 PM
(12-hour clock, no (24-hourclock) military time input) - The second, an integer argument (positive or negative) as minutes, i.e.
200
Everything is fine-and-dandy until I came across adding negative minutes. For example, I can get the correct answer when having the first argument input as 02:00 AM
, and the second argument input as -180
, which should yield the answer of 11:00 PM.
My algorithm I use is to take my input String "time"/first argument, i.e. 02:00 AM
, and convert/map that to military time (24-hour clock) for all my calculations (so I don't have to keep track of AM or PM), then I convert the entire thing to minutes, then I convert to hours and take % (modulo) with 24 (since 1 day is 24 hours) to get HOURS portion answer, and I use the previously computed minutes and % (modulo) with 60 to get the MINUTES portion of the answer.
In this example I gave above (02:00 AM) and (-180), would result in:
- 02:00AM == 120 minutes
- Add 120 minutes + (-180) minutes = -60 minutes
- Convert minutes (i.e. 60) to hours = -1 hr
- Use
Math.floorMod(-1,24)
= 23, to get the Hours portion of the answer. Using just%
gives me the wrong answer of1
... - Use -60 % 60 = 0, to get the MINUTES portion of the answer. Regular % operators works fine here
- Concatenate hours + minutes + AM/PM to return a String like
11:00 PM
I have been using the Math.floorMod(x,y)
, since the regular modulo %
operator was not working for me, when subtracting and ending up with negative numbers that I needed to take the modulo of. I was now trying different inputs like 9:13 AM
with -720
(half day) and -1440
(full day) of minutes and now I was getting some wrong answers.
It seems like when adding the minutes to a time using this modulus algorithm I always get the correct answer. Do I have to do something different now that I am essentially subtracting minutes and possibly ending up with negative numbers that I take modulo with 24?
Please let me know.