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


当前回答

const MINUTE = 60 * 1000;
new Date(Date.parse(yourDate) + numOfMins * MINUTE)

其他回答

一行代码

  var afterSomeMinutes = new Date(new Date().getTime() + minutes * 60000);

在哪里分钟是一个数字

const MINUTE = 60 * 1000;
new Date(Date.parse(yourDate) + numOfMins * MINUTE)

var now = new Date(); now.setMinutes(now.getMinutes() + 30);/ /时间戳 日期(现在);//日期对象 console.log(现在);

我总是创建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;
};

只是另一个选项,我写的:

DP_DateExtensions图书馆

如果这是您所需要的所有数据处理,那么它就太过了,但它会做您想做的事情。

支持日期/时间格式化,日期数学(添加/减去日期部分),日期比较,日期解析等。它是自由开源的。