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


当前回答

以下是ES6版本:

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

这样称呼它:

getTimeAfter30Mins();

其他回答

“添加”30分钟的一种方法是创建第二个日期对象(主要用于演示),并将分钟设置为分钟+ 30。如果第一次距离下一个小时不到30分钟,这也可以考虑调整时间。(即4:45至5:15)

const first = new Date(); console.log("第一次约会:",first. tostring ()); const second =新的日期(第一个); const newMinutes = second.getMinutes() + 30; console.log("new minutes:", newMinutes); second.setMinutes (newMinutes); console.log("second date:", second. tostring ());

对于像我这样的懒人:

Kip的答案(从上面)在coffeescript中,使用“enum”,并对同一对象进行操作:

Date.UNIT =
  YEAR: 0
  QUARTER: 1
  MONTH: 2
  WEEK: 3
  DAY: 4
  HOUR: 5
  MINUTE: 6
  SECOND: 7
Date::add = (unit, quantity) ->
  switch unit
    when Date.UNIT.YEAR then @setFullYear(@getFullYear() + quantity)
    when Date.UNIT.QUARTER then @setMonth(@getMonth() + (3 * quantity))
    when Date.UNIT.MONTH then @setMonth(@getMonth() + quantity)
    when Date.UNIT.WEEK then @setDate(@getDate() + (7 * quantity))
    when Date.UNIT.DAY then @setDate(@getDate() + quantity)
    when Date.UNIT.HOUR then @setTime(@getTime() + (3600000 * quantity))
    when Date.UNIT.MINUTE then @setTime(@getTime() + (60000 * quantity))
    when Date.UNIT.SECOND then @setTime(@getTime() + (1000 * quantity))
    else throw new Error "Unrecognized unit provided"
  @ # for chaining

新日期() var newDateObj =新日期(); (+ 30 * 60 * 1000); 游戏机。log (newDateObj);

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

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

其他解决方案:

var dateAv = new Date();
var endTime = new Date(dateAv.getFullYear(), dateAv.getMonth(), dateAv.getDate(), dateAv.getHours(), dateAv.getMinutes() + 30);