How to add 30 minutes to a JavaScript Date object?

前端 未结 20 3341
醉酒成梦
醉酒成梦 2020-11-21 23:21

I\'d like to get a Date object which is 30 minutes later than another Date object. How do I do it with JavaScript?

20条回答
  •  眼角桃花
    2020-11-22 00:14

    I always create 7 functions, to work with date in JS:
    addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears.

    You can see an example here: http://jsfiddle.net/tiagoajacobi/YHA8x/

    How to use:

    var now = new Date();
    console.log(now.addMinutes(30));
    console.log(now.addWeeks(3));
    

    These are the functions:

    Date.prototype.addSeconds = function(seconds) {
      this.setSeconds(this.getSeconds() + seconds);
      return this;
    };
    
    Date.prototype.addMinutes = function(minutes) {
      this.setMinutes(this.getMinutes() + minutes);
      return this;
    };
    
    Date.prototype.addHours = function(hours) {
      this.setHours(this.getHours() + hours);
      return this;
    };
    
    Date.prototype.addDays = function(days) {
      this.setDate(this.getDate() + days);
      return this;
    };
    
    Date.prototype.addWeeks = function(weeks) {
      this.addDays(weeks*7);
      return this;
    };
    
    Date.prototype.addMonths = function (months) {
      var dt = this.getDate();
      this.setMonth(this.getMonth() + months);
      var currDt = this.getDate();
      if (dt !== currDt) {  
        this.addDays(-currDt);
      }
      return this;
    };
    
    Date.prototype.addYears = function(years) {
      var dt = this.getDate();
      this.setFullYear(this.getFullYear() + years);
      var currDt = this.getDate();
      if (dt !== currDt) {  
        this.addDays(-currDt);
      }
      return this;
    };
    

提交回复
热议问题