Just use module 12:
function formatTimeShow(h_24) { var h = h_24 % 12; return (h < 10 ? '0' : '') + h + ':00'; }
Module ( %
) means division and acceptance of the remainder. For example, 17/12 = 1 with a remainder of 5. Thus, the result of 17% 12 is 5. And hour 17 is hour 5 in a 12-hour period.
But note that this function is not complete, as it does not work for hour 0 (or hour 12). To fix this, you need to add one more check:
function formatTimeShow(h_24) { var h = h_24 % 12; if (h === 0) h = 12; return (h < 10 ? '0' : '') + h + ':00'; }
Also note that you can easily add the meridian by seeing that the hour is less than 12 (am) or equal to / greater than (pm):
function formatTimeShow(h_24) { var h = h_24 % 12; if (h === 0) h = 12; return (h < 10 ? '0' : '') + h + ':00' + (h_24 < 12 ? 'am' : 'pm'); }
Note. All of the above assumes that the parameter of this function is an integer from 0 to 23.
source share