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


当前回答

对于像我这样的懒人:

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

其他回答

简单地,你可以在momnet库中使用这段代码:

console.log(moment(moment()).add(30,"minutes").format('MM/DD/YYYY hh:mm:ss'));

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

使用已知的现有库来处理处理时间计算所涉及的异常。我现在最喜欢的是moment.js。

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script>
 var now = moment(); // get "now"
 console.log(now.toDate()); // show original date
 var thirty = moment(now).add(30,"minutes"); // clone "now" object and add 30 minutes, taking into account weirdness like crossing DST boundries or leap-days, -minutes, -seconds.
 console.log(thirty.toDate()); // show new date
</script>

一行代码

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

在哪里分钟是一个数字

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

你好,现在是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>