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

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


当前回答

在不使用第二个变量的情况下,您可以用背部x天替换7:

let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))

其他回答

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

从今天起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));

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

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

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

第一个参数是开始日期,第二个参数是您希望增加或减少到该日期的天数

示例(1)-pass-1将日期减少一天

示例(2)-通过1将日期增加一天

const EditDay = (date: Date, num: number): Date => {
 return new Date(date.getTime() + num * 24 * 60 * 60 * 1000)
}

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

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

var d=新日期();document.write('今天是:'+d.toLocaleString());d.setDate(d.getDate()-31);document.write('<br>5天前是:'+d.toLocaleString());