Adding hours to JavaScript Date object?

前端 未结 16 1166
一生所求
一生所求 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:50
    Date.prototype.addHours= function(h){
        this.setHours(this.getHours()+h);
        return this;
    }
    

    Test:

    alert(new Date().addHours(4));
    
    0 讨论(0)
  • 2020-11-22 09:52

    The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.

    this.setUTCHours(this.getUTCHours()+h);
    

    will add h hours to this independent of time system peculiarities. Jason Harwig's method works as well.

    0 讨论(0)
  • 2020-11-22 09:55

    JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:

    Date.prototype.addHours = function(h) {
      this.setTime(this.getTime() + (h*60*60*1000));
      return this;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:55

    If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:

    //JS
    function addHoursToDate(date, hours) {
      return new Date(new Date(date).setHours(date.getHours() + hours));
    }
    
    //TS
    function addHoursToDate(date: Date, hours: number): Date {
      return new Date(new Date(date).setHours(date.getHours() + hours));
    }
    
    let myDate = new Date();
    
    console.log(myDate)
    console.log(addHoursToDate(myDate,2))

    0 讨论(0)
  • 2020-11-22 09:56

    The below code is to add 4 hours to date(example today's date)

    var today = new Date();
    today.setHours(today.getHours() + 4);
    

    It will not cause error if you try to add 4 to 23 (see the docs):

    If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly

    0 讨论(0)
提交回复
热议问题