首页 > 解决方案 > JavaScript 获取时间函数

问题描述

我的 getTime 函数可以毫无问题地显示当前的小时、分钟和秒。我的问题是如何在不同的跨度上调用小时、分钟和秒?例子

 <span id="hours" class="x"></span>
    <span id="minutes" class="y"></span>
    <span id="seconds" class="z"></span>

JavaScript 函数

   <script language="JavaScript">

        function getTime() {
            const timeNow = new Date();
            const hours = timeNow.getHours();
            const minutes = timeNow.getMinutes();
            const seconds = timeNow.getSeconds();
            let timeString = '' + ((hours > 24) ? hours - 12 : hours);
            timeString += ((minutes < 10) ? ":0" : ":") + minutes;
            timeString += ((seconds < 10) ? ":0" : ":") + seconds;
            timeString += (hours >= 12) ? "" : "";
            //timeString += (hours >= 12) ? " P.M." : " A.M.";
            return timeString;
        }

        const hoursSpan = document.getElementById('Hour');

        setInterval(() => {
            hoursSpan.textContent = getTime();
        }, 1000);

    </script>

标签: javascripthtml

解决方案


尝试这个。使变量成为全局变量以获得单独的小时分钟和秒值。您使用了错误的 id 来获取 span,并且该函数返回完整的字符串,因此仅将其拆分了几个小时

var timeNow = new Date();
            var hours = timeNow.getHours();
            var minutes = timeNow.getMinutes();
            var seconds = timeNow.getSeconds();

        function getTime() {
            timeNow = new Date();
             hours = timeNow.getHours();
             minutes = timeNow.getMinutes();
             seconds = timeNow.getSeconds();

            let timeString = '' + ((hours > 24) ? hours - 12 : hours);
            timeString += ((minutes < 10) ? ":0" : ":") + minutes;
            timeString += ((seconds < 10) ? ":0" : ":") + seconds;
            timeString += (hours >= 12) ? "" : "";
            //timeString += (hours >= 12) ? " P.M." : " A.M.";
            return timeString;
        }

        const hoursSpan = document.getElementById('hours');
         const min = document.getElementById('minutes');
          const sec = document.getElementById('seconds');

        setInterval(() => {
            hoursSpan.textContent = getTime().split(':')[0];
            min.textContent=":"+minutes;
            sec.textContent=":"+seconds;
        }, 1000);
<span id="hours" class="x"></span>
    <span id="minutes" class="y"></span>
    <span id="seconds" class="z"></span>


推荐阅读