Javascript会增加时间

Javascript add hours to time

本文关键字:时间 增加 Javascript      更新时间:2023-09-26

我有这个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

看看这个小提琴

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

下面是代码片段。

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

看看这个
此处提琴

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

javascript日期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");`