Display Time in 12 Hour Format in JavaScript

前端 未结 2 580
一个人的身影
一个人的身影 2021-01-05 21:10

I want to display Time in 12 hour format by altering the following code. i Tried Various Techniques but no luck, hope to find The solution from u guys .

<         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 21:48

    EDIT

    Based on your comments in rahul's answer...

    Update the line:

    hour: appendZero(hour),

    to

    hour: appendZero(((hour + 11) % 12) + 1) Live Demo


    Live Demo

    var formatTime = (function () {
        function addZero(num) {
            return (num >= 0 && num < 10) ? "0" + num : num + "";
        }
    
        return function (dt) {
            var formatted = '';
    
            if (dt) {
                var hours24 = dt.getHours();
                var hours = ((hours24 + 11) % 12) + 1;
                formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");            
            }
            return formatted;
        }
    })();
    
    alert(formatTime(new Date())); 
    

提交回复
热议问题