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

后端 未结 5 1696
逝去的感伤
逝去的感伤 2021-01-03 00:55

The function returns the time in 24 hour format.

function fomartTimeShow(h) {
    return h < 10 ? \"0\" + h + \":00\" : h + \":00\";
}
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 01:14

    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:

    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');
    }
    

提交回复
热议问题