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

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


当前回答

对我来说,所有的组合都能很好地使用下面的代码snipplet,该片段用于Angular-2实现,若需要增加天数,则传递正数,若需要减去负数,则传递负数

function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
    d.getFullYear(),
    d.getMonth(),
    (d.getDate() + numberofDays)
);
}

其他回答

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

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 = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);

在不使用第二个变量的情况下,您可以用背部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 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, "-");