我想获得一个日期对象,它比另一个日期对象晚30分钟。我如何用JavaScript做到这一点?
当前回答
let d = new Date();
d.setMinutes(d.getMinutes() + 30);
// console.log(d)
其他回答
var add_minutes = function (dt, minutes) {
return new Date(dt.getTime() + minutes*60000);
}
console.log(add_minutes(new Date(2014,10,2), 30).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
const MINUTE = 60 * 1000;
new Date(Date.parse(yourDate) + numOfMins * MINUTE)
这就是我所做的,似乎很有效:
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));
使用已知的现有库来处理处理时间计算所涉及的异常。我现在最喜欢的是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>