简体   繁体   中英

delete date in spreadsheet prior today's date apps script

I need to delete rows where date is before today.

I have something like this:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var data = sheet.getDataRange().getValues(); 

var today = new Date();
var date = Utilities.formatDate(new Date(today), "GMT", "yyyy-MM-dd HH:mm:ss");
// logs date 2013-06-12 19:23:53

for(n=1;n<data.length;++n){
  var start = data[n][0];
  //logs start  Wed Jul 10 19:00:00 GMT-07:00 2013
}

Thanks!

You don't show any of your data, so I'm guessing a bit.

It appears that the date format of the logs in your spreadsheet is like this:

Wed Jul 10 19:00:00 GMT-07:00 2013

That format is not automatically recognized as a date by Google Spreadsheets. However, it is OK for creating a javascript Date object, so we can do that for comparisons, like so:

new Date("Wed Jul 10 19:00:00 GMT-07:00 2013")

You've started by getting the spreadsheet data in an array, and that's good - it's quick, and we can write out the final data in one step. To remove rows from the array, use the Array.splice() method. Here's the resulting script:

function killOldLogs() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  var data = sheet.getDataRange().getValues(); 

  var today = new Date();

  // Loop over whole range, removing rows that are too old.
  // Leaves row 0, assuming it's a header row.
  for(n=data.length-1;n>0;--n){
    if (new Date(data[n][0]) < today) {
      data.splice(n,1);
    }
  }
  sheet.clearContents(); // Get rid of old contents, then write new
  sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM