Javascript 添加时间

标签 javascript time clock

我有这个应该显示时间的 javascript 代码。有用。不过,我不想增加额外的时间。假设我想增加 1 小时。

        <script type="text/javascript">
        Date.prototype.addHours = function(h) {    
           this.setTime(this.getTime() + (h*60*60*1000)); 
           return this;   
        }
        // This function gets the current time and injects it into the DOM

        function updateClock() {
            // Gets the current time
            var now = new Date();

            // Get the hours, minutes and seconds from the current time
            var hours = now.getHours();
            var minutes = now.getMinutes();
            var seconds = now.getSeconds();

            // Format hours, minutes and seconds
            if (hours < 10) {
                hours = "0" + hours;
            }
            if (minutes < 10) {
                minutes = "0" + minutes;
            }
            if (seconds < 10) {
                seconds = "0" + seconds;
            }

            // Gets the element we want to inject the clock into
            var elem = document.getElementById('clock');

            // Sets the elements inner HTML value to our clock data
            elem.innerHTML = hours + ':' + minutes + ':' + seconds;
        }
    function start(){
        setInterval('updateClock()', 200);
    }
    </script>

第一个函数计算我要添加的毫秒数,第二个函数是“实时时钟”。如何将第一个功能实现到第二个功能中,以便获得工作结果?

最佳答案

要增加小时数,请使用 setHours :

// Gets the current time
var now = new Date();

console.log("actual time:", now);

now.setHours(now.getHours() + 1)

console.log("actual time + 1 hour:", now);

供引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours

关于Javascript 添加时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31383993/

相关文章:

mysql - 如何查询时间是否存储为varchar?

java - java中的无限时间值?

c++ - C++ 中带线程的时钟函数

c++ - 在 QT 中创建一个简单的时钟

javascript - 获取自定义事件的 "this"引用

javascript - 使用 Web 动画动画 DOM 属性 (scrollTop)

javascript - dda算法——光线转换

javascript - jQuery 返回窗口对象

perl - 使用Perl将2天添加到今天

c++ - timespec.tv_sec 总是返回 0