JavaScript的Date对象没有实现任何类型的add函数,这让我感到惊讶。

我只是想要一个函数,可以这样做:

var now = Date.now(); var fourHoursLater = now.addHours(4); 函数Date.prototype.addHours(h) { //我如何实现这个? }

我只是想要一些指路的指点。

我需要做字符串解析吗? 我可以使用setTime吗? 毫秒呢?

是这样的:

new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?

这看起来真的很奇怪——它真的有用吗?


当前回答

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

测试:

alert(new Date().addHours(4));

其他回答

JavaScript本身有糟糕的日期/时间API。尽管如此,你可以在纯JavaScript中这样做:

Date.prototype.addHours = function(h) {
  this.setTime(this.getTime() + (h*60*60*1000));
  return this;
}

你可以使用Moment.js库。

var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();

两小时后找个约会对象,一句话。

您需要向new Date传递毫秒数。

let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));

        or

let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );

let nowDate = new Date(); let expiryDate = new Date(new Date()。setHours(new Date().getHours() + 2)); let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000)); console.log(‘现在’,nowDate); console.log(“到期”,expiryDate); console.log('expiry 2', expiryDate2);

我觉得这个应该能搞定

var nextHour =日期。 游戏机。log (nextHour)

我也认为原来的对象不应该被修改。因此,为了节省未来的人力,这里有一个基于Jason Harwig和Tahir Hasan回答的综合解决方案:

Date.prototype.addHours= function(h){
    var copiedDate = new Date();
    copiedDate.setTime(this.getTime() + (h*60*60*1000)); 
    return copiedDate;
}