小时未显示00格式

时间:2018-03-03 15:15:17

标签: javascript

我有这段代码:

 <a href="#"><span id="live_time">Server Time: <strong><?php echo date('h:i:s A'); ?></strong></span></a>
                    <script type="text/javascript">
                        // use php to get the server time
                        var serverdate = new Date('<?php echo date('F d, Y h:i:s'); ?>');
                        function refresh_time(){
                            serverdate.setSeconds(serverdate.getSeconds() + 1);
                            var hh=serverdate.getHours();
                            var m=serverdate.getMinutes();
                            var s=serverdate.getSeconds();
                               m=checkTime(m);
                            s=checkTime(s);
                            var dd = " AM";
                            var h = hh;
                            if (h >= 12) {
                                h = hh-12;
                                dd = " PM";
                            }
                            if (h == 0) {
                                h = 12;
                            }


                            var output = h+":"+m+":"+s+""+dd;
                            document.getElementById("live_time").innerHTML = 'Server Time: <strong>'+output+'</strong>';
                        }
                            function checkTime(i) {
                                if (i < 10) {i = "0" + i};
                                return i;
                            }

                        window.onload = function(){
                          setInterval("refresh_time()", 1000);
                        }



                    </script>

当我第一次访问页面时它会在07:11:14 AM显示我一秒钟后变为7:11:15 AM如何在H格式的每次刷新时输出?像07:11:15?

2 个答案:

答案 0 :(得分:0)

您可以使用ES8 padStart()将小时填充为0。

&#13;
&#13;
var h = "5";
console.log(h.padStart(2, "0"));
&#13;
&#13;
&#13;

或者如果不使用旧语法

&#13;
&#13;
var h = "5";
console.log(h.length == 1 ? "0"+h : h);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

只需手动添加0

&#13;
&#13;
var date = new Date();
currentHours = date.getHours();
var currentHours2 = 6;
var currentHours3 = 18;
currentHours = ("0" + currentHours).slice(-2);
currentHours2 = ("0" + currentHours2).slice(-2);
currentHours3 = ("0" + currentHours3).slice(-2);
console.log(currentHours)
console.log(currentHours2)
console.log(currentHours3)
&#13;
&#13;
&#13;