How to convert time from 24 hour format to 12 hour format using javascript?

The function returns the time in 24 hour format.

function fomartTimeShow(h) { return h < 10 ? "0" + h + ":00" : h + ":00"; } 

returns time in 24-hour format. I want the time to be converted to 12 hour format.
Anyhelp would be greatly appreciated.
Thanks.

+6
source share
4 answers

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.

+13
source

You can try something like the following:

 function fomartTimeShow(h) { var ampm = "am" if (h >= 12) ampm = "pm" h = h % 12; if (h == 0) h = 12; return h ":00" + ampm; } 
+2
source
 function fomartTimeShow(h) { var s = (h % 24 < 12) ? "am" : "pm", h = h % 12 || 12; return (h < 10 ? "0" + h : h) + ":00" + " " + s; } 
+1
source

I am sure that this will work as a more concise formulaic version of Ben Lee's answer, including for h = 0 and h = 12 cases:

 function fomartTimeShow(h_24) { var h = ((h_24 + 11) % 12)+1; return (h < 10 ? '0' : '') + h + ':00'; } 

or including am / pm:

 function fomartTimeShow(h_24) { var h = ((h_24 + 11) % 12)+1; return (h < 10 ? '0' : '') + h + ':00' + (h_24 < 12 ? 'am' : 'pm'); } 
0
source

Source: https://habr.com/ru/post/909620/


All Articles