Javascript会增加时间

Nie*_*ann 6 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>
Run Code Online (Sandbox Code Playgroud)

第一个函数计算我要添加的milisecons,第二个函数是"live clock".如何将第一个函数实现到第二个函数中,以便得到工作结果?

ben*_*ben 7

添加小时,使用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);
Run Code Online (Sandbox Code Playgroud)

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


Shr*_*kla 5

看看这个小提琴

构造函数Date(milliseconds)class Date可以在这里使用。

这是片段。

var now = new Date();
alert(now);

var milliseconds = new Date().getTime() + (1 * 60 * 60 * 1000);
var later = new Date(milliseconds);
alert(later);
Run Code Online (Sandbox Code Playgroud)