有没有一种简单的方法来获取olain JavaScript日期(例如今天)并返回X天?

例如,如果我想计算今天前5天的日期。


当前回答

上面的答案导致了我的代码中的一个错误,在这个月的第一天,它会在当月设置一个未来的日期。这是我所做的,

curDate = new Date(); // Took current date as an example
prvDate = new Date(0); // Date set to epoch 0
prvDate.setUTCMilliseconds((curDate - (5 * 24 * 60 * 60 * 1000))); //Set epoch time

其他回答

它是这样的:

var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);

设置日期时,日期转换为毫秒,因此需要将其转换回日期:

这种方法还考虑了新年变化等因素。

function addDays( date, days ) {
    var dateInMs = date.setDate(date.getDate() - days);
    return new Date(dateInMs);
}

var date_from = new Date();
var date_to = addDays( new Date(), parseInt(days) );

一些现有的解决方案很接近,但并不完全符合我的要求。此函数可处理正值或负值,并处理边界情况。

function addDays(date, days) {
    return new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate() + days,
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
    );
}

我为Date制作了这个原型,这样我就可以传递负值来减去天数,传递正值来添加天数。

if(!Date.prototype.adjustDate){
    Date.prototype.adjustDate = function(days){
        var date;

        days = days || 0;

        if(days === 0){
            date = new Date( this.getTime() );
        } else if(days > 0) {
            date = new Date( this.getTime() );

            date.setDate(date.getDate() + days);
        } else {
            date = new Date(
                this.getFullYear(),
                this.getMonth(),
                this.getDate() - Math.abs(days),
                this.getHours(),
                this.getMinutes(),
                this.getSeconds(),
                this.getMilliseconds()
            );
        }

        this.setTime(date.getTime());

        return this;
    };
}

因此,为了使用它,我可以简单地写下:

var date_subtract = new Date().adjustDate(-4),
    date_add = new Date().adjustDate(4);

我创建了一个日期操作函数。你可以加或减任何天数、小时、分钟。

function dateManipulation(date, days, hrs, mins, operator) {
   date = new Date(date);
   if (operator == "-") {
      var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
      var newDate = new Date(date.getTime() - durationInMs);
   } else {
      var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
      var newDate = new Date(date.getTime() + durationInMs);
   }
   return newDate;
 }

现在,通过传递参数来调用此函数。例如,这里有一个函数调用,用于从今天起3天内获取日期。

var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");