我想获得一个日期对象,它比另一个日期对象晚30分钟。我如何用JavaScript做到这一点?


当前回答

let d = new Date();
d.setMinutes(d.getMinutes() + 30);

// console.log(d)

其他回答

事情就是这么简单;

let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));
var d1 = new Date (),
    d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 30 );
alert ( d2 );

没有实用程序的一行程序:

new Date(+new Date() + 60000*15) // +15 minutes

以下是ES6版本:

let getTimeAfter30Mins = () => {
  let timeAfter30Mins = new Date();
  timeAfter30Mins = new Date(timeAfter30Mins.setMinutes(timeAfter30Mins.getMinutes() + 30));
};

这样称呼它:

getTimeAfter30Mins();

我总是创建7个函数,在JS中使用date: addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears。

你可以在这里看到一个例子:http://jsfiddle.net/tiagoajacobi/YHA8x/

使用方法:

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

这些是函数:

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;
};