0

The problem that i am having here is that when i minus back to then end of the month, instead of going back to the 29 or 28 of last month the program starts to minus months instead of days. Bellow is my full code and below that is the output it produces in the google spread sheet.

function trying(){ 

  var date = new Date(); 
  var datechange = new Date();
  var array = new Array(7);

 for (var i = 0; i < 7; i++) {
    array[i] = new Array(0);
  }

  for ( var i = 0; i < 7; i++){ 
   days = i + 8
   datechange.setDate(date.getDate() - days);
   var tabName = Utilities.formatDate(datechange, 'MST', 'yyyy-MM-dd').toString(); 
       array[i][0] = tabName;
    }

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Want");
  sheet.getRange("B2:B8").setValues(array); 



}

This are the dates that are produced.

05/07/2012 04/07/2012 03/07/2012 02/07/2012 01/07/2012 30/06/2012 30/05/2012

4

3 回答 3

1

Date.getDate() returns the date (1-31) - so what you are doing is not correct.

Instead try this:

var ONE_DAY = 24 * 60 * 60 * 1000; //in milliseconds
for ( var i = 0; i < 7; i++){ 
  days = i + 8
  datechange.setDate(date.getTime() - (days * ONE_DAY));
  var tabName = Utilities.formatDate(datechange, 'MST', 'yyyy-MM-dd').toString(); 
     array[i][0] = tabName;
}
于 2012-07-13T17:15:04.170 回答
1

您必须datechange在循环内部定义,而不是在外部定义:

var date = new Date();

for ( var i = 0; i < 30; i++){ 
   days = i + 8
   var datechange = new Date();
   datechange.setDate(date.getDate() - i);
   console.log(datechange);
   }
于 2012-07-13T22:55:23.877 回答
0

这就是 JavaScript 日期的工作方式。请参阅此处了解完整详情。

于 2012-07-13T16:56:51.910 回答