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


当前回答

var myDate= new Date();
var MyNewDate = new Date 
(myDate.getFullYear(),myDate.getMonth(),myDate.getDate(),myDate.getMinutes()+10,01,01)

其他回答

你可以这样做:

let 30tyminutes = 30 * 60 * 1000;//将30分钟转换为毫秒 let date1 = new Date(); let date2 = new Date(date1.getTime() + 30tyminutes); console.log (date1); console.log (date2);

新日期() 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>

对于像我这样的懒人:

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 d = new Date(); var v = new Date(); v.setMinutes (d.getMinutes () + 30); console.log (v)