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

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

    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.

    function convertTo12Hour(oldFormatTime) {
        console.log("oldFormatTime: " + oldFormatTime);
        var oldFormatTimeArray = oldFormatTime.split(":");
    
        var HH = parseInt(oldFormatTimeArray[0]);
        var min = oldFormatTimeArray[1];
    
        var AMPM = HH >= 12 ? "PM" : "AM";
        var hours;
        if(HH == 0){
          hours = HH + 12;
        } else if (HH > 12) {
          hours = HH - 12;
        } else {
          hours = HH;
        }
        var newFormatTime = hours + ":" + min + " " + AMPM;
        console.log(newFormatTime);
    }
    

提交回复
热议问题