tda
tda

Reputation: 241

Google Sheets: Pulling rows based on date

I have a form below...

Form

That prints responses out to the following spreadsheet

Sheet

I have this current script that takes the rows and prints them all in a google doc:

function saveAsDOC() {
  var fileName = "Announcements Test File";
  var doc = DocumentApp.create(fileName);
  SpreadsheetApp.getActiveSpreadsheet().toast('Generating file..', 'Status', 3);

  // Get the range in the spreadsheet
  var ws = SpreadsheetApp.getActiveSpreadsheet().getDataRange();
  try {
    var data = ws.getValues();

    // Print the annoucements in a loop
    if (data.length > 1) {
      for (var row = 1; row < data.length; row++) {
        if(new Date(data[row][2]) <= new Date()) {
          for (var col = 1; col < data[row].length; col++) {
            if(data[row][col]!=""){
              doc.appendParagraph(data[row][col]);
              doc.appendParagraph("")
            }
          }
        }
      }
    }
  }

  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }
}

I would like to modify this script so that it only prints the rows where the 'Start Date' is today & following days up until the 'End Date'. There is nothing on the internet that I have found to help me, so I came here.

Edit: Updated with answer.

Upvotes: 0

Views: 1906

Answers (1)

Wim den Herder
Wim den Herder

Reputation: 1305

new Date() will give the date object of "now". Then simple comparison will do the work:

if(new Date(data[row][2]) > new Date() || new Date(data[row][3]) > new Date())

I was not sure about what you meant, but this is: if startDate is in the future or endDate is in the future.

Complete Code

function saveAsDOC() {
  // Prompts the user for the file name
  var fileName = "TEMP weggooien";
  var doc = DocumentApp.create(fileName);

  // Get the range in the spreadsheet
  var ws = SpreadsheetApp.getActiveSpreadsheet().getDataRange();
  try {
    var data = ws.getValues();

    // Loop through the data in the range and create paragraphs with the appropriate heading
    if (data.length > 1) {
      for (var row = 1; row < data.length; row++) {
        if(new Date(data[row][2]) > new Date() || new Date(data[row][3]) > new Date()) {
          for (var col = 1; col < data[row].length; col++) {
            if(data[row][col]!=""){
              doc.appendParagraph(data[row][col]);
            }
          }
        }
      }
    }
  }
  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }
}

Upvotes: 2

Related Questions