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 */)?

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


当前回答

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

其他回答

Datejs库中有一个添加。

这里是JavaScript日期方法。kennebec明智地提到了getHours()和setHours();

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

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

您甚至可以在添加2小时后使用moment函数将日期格式化为所需的格式。

var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
    
console.log(time);

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

您需要向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);

对于JavaScript中简单的加/减小时/分钟函数,试试这个:

function getTime (addHour, addMin){
    addHour = (addHour ? addHour : 0);
    addMin = (addMin ? addMin : 0);
    var time = new Date(new Date().getTime());
    var AM = true;
    var ndble = 0;
    var hours, newHour, overHour, newMin, overMin;

    // Change form 24 to 12 hour clock
    if(time.getHours() >= 13){
        hours = time.getHours() - 12;
        AM = (hours>=12 ? true : false);
    }else{
        hours = time.getHours();
        AM = (hours>=12 ? false : true);
    }

    // Get the current minutes
    var minutes = time.getMinutes();

    // Set minute
    if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
        overMin = (minutes + addMin) % 60;
        overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
        if(overMin < 0){
            overMin = overMin + 60;
            overHour = overHour-Math.floor(overMin/60);
        }
        newMin = String((overMin<10 ? '0' : '') + overMin);
        addHour = addHour + overHour;
    }else{
        newMin = minutes + addMin;
        newMin = String((newMin<10 ? '0' : '') + newMin);
    }
    // Set hour
    if((hours + addHour >= 13) || (hours + addHour <= 0)){
        overHour = (hours + addHour) % 12;
        ndble = Math.floor(Math.abs((hours + addHour)/12));
        if(overHour <= 0){
            newHour = overHour + 12;
            if(overHour == 0){
                ndble++;
            }
        }else{
            if(overHour == 0){
                newHour = 12;
                ndble++;
            }else{
                ndble++;
                newHour = overHour;
            }
        }
        newHour = (newHour<10 ? '0' : '') + String(newHour);
        AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
    }else{
        AM = (hours + addHour == 12 ? !AM : AM);
        newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
    }
    var am = (AM) ? 'AM' : 'PM';
    return new Array(newHour, newMin, am);
};

这可以不带参数地使用来获取当前时间:

getTime();

或者使用参数来获得添加分钟/小时的时间:

getTime(1, 30); // Adds 1.5 hours to current time
getTime(2);    // Adds 2 hours to current time
getTime(0, 120); // Same as above

即使是负时间也可以:

getTime(-1, -30); // Subtracts 1.5 hours from current time

这个函数返回一个数组:

array([Hour], [Minute], [Meridian])