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

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


当前回答

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

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

其他回答

get moment.js。所有酷孩子都使用它。它有更多的格式选项等。在哪里

var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');

可选择的转换为JS Date obj以进行角度绑定。

var date = new Date(dateMnsFive.toISOString());

可选择的总体安排

var date = dateMnsFive.format("YYYY-MM-DD");

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

试试这样的

dateLimit = (curDate, limit) => {
    offset  = curDate.getDate() + limit
    return new Date( curDate.setDate( offset) )
}

currDate可以是任何日期

限制可以是天数的差异(未来为正值,过去为负值)

将日期拆分为多个部分,然后返回一个具有调整值的新日期

function DateAdd(date, type, amount){
    var y = date.getFullYear(),
        m = date.getMonth(),
        d = date.getDate();
    if(type === 'y'){
        y += amount;
    };
    if(type === 'm'){
        m += amount;
    };
    if(type === 'd'){
        d += amount;
    };
    return new Date(y, m, d);
}

记住,月份是以零为基础的,但日子不是。即新日期(2009,1,1)==2009年2月1日,新日期(2009,1,0)==2009年1月31日;

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

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