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


当前回答

事情就是这么简单;

let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));

其他回答

以下是ES6版本:

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

这样称呼它:

getTimeAfter30Mins();

下面是我的一句话:

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

也许像这样?

var d = new Date(); var v = new Date(); v.setMinutes (d.getMinutes () + 30); console.log (v)

事情就是这么简单;

let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));

最简单的解决方法是认识到在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)