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

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


当前回答

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

其他回答

我的里程数很好。js:

http://www.datejs.com/

d = new Date();
d.add(-10).days();  // subtract 10 days

美好的

网站包含此功能:

Datejs不只是解析字符串,它将字符串干净利落地分成两部分

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

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

使用现代JavaScript函数语法

const getDaysPastDate=(daysBefore,date=new date)=>新日期(date-(1000*60*60*24*daysBefore));console.log(getDaysPastDate(1));//昨天

var my date = new Date().toISOString().substring(0, 10);

它只能给你2014-06-20这样的日期。希望会有所帮助

如果你想把这一切都放在一行。

从今天起5天

//past
var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));

特定日期后5天

 var pastDate = new Date('2019-12-12T00:00:00');

 //past
 var fiveDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5));
 //future
 var fiveDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));

我写了一个你可以使用的函数。

函数AddOrSubactDays(startingDate,number,add){if(添加){返回新日期(newDate().setDate(startingDate.getDate()+number));}其他{返回新日期(newDate().setDate(startingDate.getDate()-number));}}console.log('Today:'+new Date());console.log('Future:'+AddOrSubactDays(new Date(),5,true));console.log('Last:'+AddOrSubactDays(new Date(),5,false));