Adding hours to JavaScript Date object?

前端 未结 16 1418
一生所求
一生所求 2020-11-22 09:00

It amazes me that JavaScript\'s Date object does not implement an add function of any kind.

I simply want a function that can do this:

var now = Date         


        
16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 09:55

    It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.

    Date.prototype.addHours= function(h){
        var copiedDate = new Date(this.getTime());
        copiedDate.setHours(copiedDate.getHours()+h);
        return copiedDate;
    }
    

    This way you can chain a bunch of method calls without worrying about state.

提交回复
热议问题