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

后端 未结 5 1713
逝去的感伤
逝去的感伤 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:10

    Just use modulus 12:

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

    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:

    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 add a meridian easily, by seeing whether the hour is less than 12 (am) or equal to/greater (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 is assuming the parameter to this function is an integer between 0 and 23.

提交回复
热议问题