The function returns the time in 24 hour format.
function fomartTimeShow(h) {
return h < 10 ? "0" + h + ":00" : h + ":00";
}
returns the time in 24 hour format. I want the time to be converted in 12 hour format.
Anyhelp would be greatly appreciated.
Thanks.
I'm pretty sure this will work as an even more concise formulaic version of Ben Lee's answer, including for the h=0 and h=12 cases:
or including am/pm:
Just use modulus 12:
Modulus (
%
) means divide and take remainder. For example 17 / 12 = 1 with remainder 5. So the result of 17 % 12 is 5. And hour 17 is hour 5 in 12-hour time.But note that this function is not complete since it doesn't work for hour 0 (or hour 12). To fix it you have to add in another check for that:
Also note that you can add a meridian easily, by seeing whether the hour is less than 12 (am) or equal to/greater (pm):
Note: All of the above is assuming the parameter to this function is an integer between 0 and 23.
In case if you are getting time like this "16:26", "12:50", "05:23", etc. Then, you can easily convert them into 12 hour format like "4:26 PM", "12:50 PM", "05:23 AM", etc. with AM/PM through this function.
You could try something like the following: