我们怎样才能在javascript中获得30天之前的所有日期

时间:2015-07-22 07:41:39

标签: javascript jquery

我有以下代码作为参考 我想在日期列表前30天获取详细信息。 我该怎么替换?

   Date.prototype.addDays = function(days) {
       var dat = new Date(this.valueOf())
       dat.setDate(dat.getDate() + days);
       return dat;
   }

   function getDates(startDate, stopDate) {
      var dateArray = new Array();
      var currentDate = startDate;
      while (currentDate <= stopDate) {
        dateArray.push(currentDate)
        currentDate = currentDate.addDays(1);
      }
      return dateArray;
    }

var dateArray = getDates(new Date(), (new Date()).addDays(2));
for (i = 0; i < dateArray.length; i ++ ) {
    alert (dateArray[i]);
}

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
Date.prototype.setDays = function(days) {
       var dat = new Date(this.valueOf())
       dat.setDate(dat.getDate() + days);
       return dat;
 }

   function getDates(startDate, counter) {
      var dateArray = new Array();
      var currentDate = startDate;
	  //To get non-Zero Index to run the loop 
	  var index=(counter > 0 ? counter : -counter);
      while (index > 0) {
        // Do not push the current date ::Optional dateArray.push(currentDate)
		//Will send days as +(after) and -(before)
        currentDate = currentDate.setDays(counter > 0 ? 1 : -1);
		
		//Push the date after the operation
		dateArray.push(currentDate);
		
		--index;
      }
      return dateArray;
    }

var dateArray = getDates(new Date(), 2);
$.each(dateArray||[],function(index,dateItem){
	console.log("Date "+ dateItem);	
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

以下是您可以尝试发送差异的代码。 让我们说+30天或-30天。