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


当前回答

这是IsoString的版本:

console.log(new Date(new Date().setMinutes(new Date().getMinutes() - (30))).toISOString());

其他回答

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

下面是我的一句话:

console.log('time: ', new Date(new Date().valueOf() + 60000))

最简单的解决方法是认识到在javascript中日期只是数字。它开始于1969年12月31日星期三18:00:00 GMT-0600 (CST)。每1代表一毫秒。您可以通过获取值并使用该值实例化一个新日期来增加或减少毫秒数。用这种思维,你很容易就能搞定。

const minutesToAdjust = 10;
const millisecondsPerMinute = 60000;
const originalDate = new Date('11/20/2017 10:00 AM');
const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));

console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)

事情就是这么简单;

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