Search code examples
mathmodulo

More elegant modulo conversion between 24hr time and 12hr time?


Converting 24-hour time (like military time) to 12-hr (clock-face) time seems like a perfect place to use the modulo operator, but I can't figure out a purely mathematical way to map 0 to 12 (so have hours 1 through 12 instead of 0 through 11). The best I've been able to come up with are either (in Ruby)

modHour = militaryHour % 12
if modHour == 0
  clockHour = 12
else
  clockHour = modHour
end

or,

hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
clockHour = hours[ militaryHour % 12 ]

It seems like there must be some way to accomplish this shift mathematically, but I can't figure it out.


Solution

  • I think

    hour12 = 12 - ((- hour24) % 12)
    

    should work.