Javascript会增加时间

时间:2015-07-13 12:54:42

标签: 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>

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

4 个答案:

答案 0 :(得分:7)

要添加小时数,请使用setHours

&#13;
&#13;
// 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);
&#13;
&#13;
&#13;

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

答案 1 :(得分:4)

查看此fiddle

此处可以使用Date(milliseconds)的构造函数class Date

以下是摘录。

&#13;
&#13;
var now = new Date();
alert(now);

var milliseconds = new Date().getTime() + (1 * 60 * 60 * 1000);
var later = new Date(milliseconds);
alert(later);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

看看这个 fiddle here

var todayDate = new Date();
alert("After adding ONE hour : "+new Date(todayDate.setHours(todayDate.getHours()+1)) );

答案 3 :(得分:0)

javascript date API即将完成,它的现有方法可用于为此API添加其他功能,有人说这很乏味,但事实并非如此。

为了在日期中添加方法,我们将访问此API的原型,

像这样

Date.prototype.addTime = function(str){
    function parse(str){
        let arr = (typeof str == 'number')?[str]:str.split(":").map(t=>t.trim());
        arr[0] = arr[0] || 0;
        arr[1] = arr[1] || 0;
        arr[2] = arr[2] || 0;
        return arr
    }
    function arrToMill(arr){
        let [h,m,s] = arr;
        return (h*60*60*1000) + (m*60*1000) + (s*1000); 
    }
    let date = new Date(this.getTime());
    let parsed = parse(str);
    date.setTime(date.getTime() + arrToMill(parsed));
    return date;
}

让它摇滚起来。 该功能是不变的

let date = new Date();
date.addTime(1);
date.addTime("01:00");`