简体   繁体   中英

How do I loop through a single column of dates in Google Sheets and then send an email based on the date

I am trying to loop through a single column of dates (in format dd/mm/yyyy) in a range C2:C

Inside the loop, I want to send an email if the date is over one year old as the membership has expired.

The email address for the member is in the adjacent column

I am having problems working with dates and cannot figure out how to make the if statement understand if the date is over one year old. I can do this on a spreadsheet but it doesn't translate to JS

I'm not even close to having a working method on this, I don't fully understand all the getActive, getRange and getDataValues parts and can't find a place that explains using these. Any pointers in where I can look would be great.

I find it easiest to convert dates to milliseconds using .getTime() .

This return the number of milliseconds since 1970/01/01. Ref here .

So what I would do is:

function sendMailIfMembershipExpired() {

  var today = new Date().getTime(); // Get today's date
  var yearInMs = 365 * 24 * 60 * 60 * 1000; // 1yr worth of milliseconds

  // Get sheet with data;  
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("NAME_OF_SHEET_WITH_DATA");

  // Get the data from the sheet
  // Col C for dates and Col D for email addresses
  var data = ss.getRange("C2:D").getValues();

  // Define variables
  var dateInCell, difference, emailTo;

  // Loop through data
  for (var row = 0; row < data.length; row++) { // data array starts at 0

    dateInCell = new Date(data[row][0]).getTime(); // Get date from sheet in milliseconds

    difference = today - dateInCell; // Get difference in millisenconds

    if ( difference > yearInMs ) { // Check if membership has expired

      emailTo = data[row][1]; // Get email address

      GmailApp.sendEmail(emailTo, "Membership expired", "Hello, your membership has expired"); // Send email

    }    
  }
}

The Google Apps Script docs are pretty good. Refs are here

  1. Get Sheet by name

  2. Get values from sheet

  3. Send mail


Edit

@dwmorrin is correct.

As long as the dates in the sheet are formatted as dates and not text, you can simplify to

dateInCell = data[row][0].getTime(); // Get date from sheet in milliseconds

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