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

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


当前回答

请参见以下代码,从当前日期减去天数。此外,根据减去的日期设置月份。

var today = new Date();
var substract_no_of_days = 25;

today.setTime(today.getTime() - substract_no_of_days* 24 * 60 * 60 * 1000);
var substracted_date = (today.getMonth()+1) + "/" +today.getDate() + "/" + today.getFullYear();

alert(substracted_date);

其他回答

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

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

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

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 my date = new Date().toISOString().substring(0, 10);

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

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

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

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

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