Filter array by date with google app script

后端 未结 3 1836
南笙
南笙 2021-01-22 03:08

i\'ve a google spreadsheet that is a 2 columns table that has on column A dates (i\'m sure that are dates, and all the date functions works fine on all the column) and on column

相关标签:
3条回答
  • 2021-01-22 03:47

    I've created a similar spreadsheet (first column with text, second with dates) and the following script:

    function myFunction() {
      var sheet =  SpreadsheetApp.openById("…");
      var ss    = sheet.getSheetByName("testing");
      var range = ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn());
      var data  = range.getValues();
    
      var filtered = data.filter(function (row) {
        return row[1].getFullYear() === 2016;
      });
    
      Logger.log(filtered);
    }
    

    And it works as long as the second column is of Date type (Format→Number→Date). I get the error you've described if I change the type to Text. If there are no errors in your code (like .getFullYear instead of .getFullYear() as it's a function, not a property), I think the data (not the variable, but the spreadsheet's data) is not of Date type.

    0 讨论(0)
  • 2021-01-22 03:51

    Try this

    var filtered = data.filter(function (row) {
    
      var d = new Date( row[1] ); // change text to Date object
      return  d.getFullYear() === 2016; // then compare
    
    });
    
    0 讨论(0)
  • 2021-01-22 04:00

    The Date methods will work on a Date will work on a Date object, not text. What you have in the variable dataRow[1] is simply a string, not a Date object. Hence it doesn't have that method.

    0 讨论(0)
提交回复
热议问题