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


当前回答

下面是我的一句话:

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

其他回答

这就是我所做的,似乎很有效:

Date.prototype.addMinutes = function(minutes) {
    var copiedDate = new Date(this.getTime());
    return new Date(copiedDate.getTime() + minutes * 60000);
}

然后你可以这样调用它:

var now = new Date();
console.log(now.addMinutes(50));

以下是ES6版本:

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

这样称呼它:

getTimeAfter30Mins();

事情就是这么简单;

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

我知道这个话题太老了。但是我非常确定有一些开发人员仍然需要这个,所以我为您制作了这个简单的脚本。 希望你喜欢!

你好,现在是2020年,我做了一些修改,希望现在能更好地帮助你!

你好,现在是2022年,我又回来解决了一些问题,并为方法和函数提供了更好的命名。

function addTimeToDate(addedTime, date){ let generatedTime = date.getTime(); if(addedTime.seconds) generatedTime += 1000 * addedTime.seconds; //check for additional seconds if(addedTime.minutes) generatedTime += 1000* 60 * addedTime.minutes;//check for additional minutes if(addedTime.hours) generatedTime += 1000 * 60 * 60 * addedTime.hours;//check for additional hours return new Date(generatedTime); } Date.prototype.addTime = function(addedTime){ return addTimeToDate(addedTime, this); } let futureDate = new Date().addTime({ hours: 16, //Adding one hour minutes: 45, //Adding fourty five minutes seconds: 0 //Adding 0 seconds return to not adding any second so we can remove it. }); <button onclick="console.log(futureDate)">Travel to the future</button>

这是IsoString的版本:

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