ivan
ivan

Reputation: 6322

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.

Upvotes: 2

Views: 2673

Answers (4)

HNipps
HNipps

Reputation: 521

If you came here looking for how to do the opposite, like me, here's what I came up with:

Where newTime format is "hh:mm a", e.g. "12:00 AM":

const [timeOnly, period] = newTime.split(' ');
const [hoursStr, minutes] = timeOnly.split(':');
const hoursNum = parseInt(hoursStr);
const hours = period === 'PM' ? ((hoursNum % 12) + 12) % 24 : (hoursNum % 12) % 24;

The only edge case it doesn't handle is if newTime === "0:00 PM". Otherwise it works well.

Upvotes: 0

BinaryPatrick
BinaryPatrick

Reputation: 512

The answer by Eric Jablow did not yield the correct answer for me. I found that this inline function worked though.

int militaryTime = 14;
int civilianTime = ((24hr - 1) % 12) + 1;

Upvotes: 1

Eric Jablow
Eric Jablow

Reputation: 7899

I think

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

should work.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799230

(pardon my Python...)

>>> for hr in range (24):
...   print hr, (hr + 11) % 12 + 1
... 
0 12
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 1
14 2
15 3
16 4
17 5
18 6
19 7
20 8
21 9
22 10
23 11

Upvotes: 4

Related Questions