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

其他回答

SPRBRN是正确的。为了解释月和年的开始/结束,您需要转换为Epoch和返回。

你可以这样做:

var milliseconds = 0;          //amount of time from current date/time
var sec = 0;                   //(+): future
var min = 0;                   //(-): past
var hours = 2;
var days = 0;

var startDate = new Date();     //start date in local time (we'll use current time as an example)

var time = startDate.getTime(); //convert to milliseconds since epoch

//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);

var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now

或者在一行中完成(其中变量名与上面相同:

var newDate =
    new Date(startDate.getTime() + millisecond +
        1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));

通过返回Date对象的副本而不是改变其参数,使addHours方法不可变可能会更好。

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

通过这种方式,您可以将一堆方法调用链接起来,而不用担心状态。

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

下面的代码将为一个日期增加4个小时(例如今天的日期):

var today = new Date();
today.setHours(today.getHours() + 4);

如果您尝试将4添加到23(请参阅文档),则不会导致错误:

如果指定的参数超出预期范围,setHours()将尝试更新date对象中的日期信息