Programming Tips - How can I convert a 24-hour time time to a 12-hour time?

Date: 2014sep12 Language: C/C++ Q. How can I convert a 24-hour time time to a 12-hour time? A. Its only tricky around midnight.
// Convert a 24-hour time to a 12-hour time // (eg 13 becomes 1pm) int Hour24ToHour12(const int hour24) { int hour = hour24; if (hour == 0) hour = 12; // at 30 minutes into the day we want 12:30 not 00:30 if (hour > 12) hour -= 12; return hour; }
Or if you want "am" / "pm" also
void Hour24ToHour12Str(const int hour24, LPSTR buf, const size_t size) { int hour12 = Hour24ToHour12(hour24); char part = (hour24 >= 12) ? 'p' : 'a'; _snprintf(buf, size, "%d%cm", hour12, part); }