如何从单元格中提取日期并将其与今天的日期进行比较

时间:2019-04-11 18:21:35

标签: date google-apps-script google-sheets

我正在使用电子表格来管理认证的到期日期。我想在员工的证书在90天内到期时向其发送电子邮件。我只想发送一封电子邮件。我正在努力从单元格中获取日期,并将其与今天的日期进行比较。

如果MS中的今天+ 90天是> MS中的证书到期日期,我想发送电子邮件。

我开始使用模板来防止发送重复的电子邮件。我让if &&与两个单元格中的单词一起工作。我正在努力使日期生效。我尝试使用getTime()获取MS中的日期,但getValues().getTime返回错误。

var EMAIL_SENT = 'EMAIL_SENT';

var NintyDayInMs = 90*24*60*60*100;
var Today = new Date().getTime();
var expired = Today+NintyDayInMs;

/**
 * Sends non-duplicate emails with data from the current spreadsheet.
 */
function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2; // First row of data to process
  var numRows = 2; // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 4);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[0]; // First column
    var message = row[1]; // Second column
    var emailSent = row[2]; // Third column
    var exp = row[3]; // Fourth column
    var expDate = exp.getTime();

    if (emailSent != EMAIL_SENT && expDate < expired) { // Prevents 
sending duplicates
      var subject = 'Sending emails from a Spreadsheet';
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is 
 interrupted
      SpreadsheetApp.flush();
    }
  }
}

我当前的代码导致

  

TypeError:在对象(单元格中的日期)中找不到函数getTime。   (第26行,文件“代码”)

1 个答案:

答案 0 :(得分:1)

阅读Adding Days to a Date - Google Script可以更好地理解脚本中的日期算术。

  

缺陷在于试图链接到期日期。代替:
  var exp = row[3]; // Fourth column
  var expDate = exp.getTime();

     

仅使用:
  var expDate = new Date(row[3]); // make the sheet value a date object

然后其余的自然而然地...

var expDate = new Date(row[3]); // make the sheet value a date object    
Logger.log("expiry = "+expDate);    
var today = new Date();    
Logger.log("today = "+today);    
var today90 = new Date(today.getTime()+90*3600000*24);// 90 days from today    
Logger.log("today90 = "+today90);    
if ((today90 > expDate) && (emailSent!=EMAIL_SENT)){    
   Logger.log("send the email");    
}    
else    
{    
   Logger.log("don't send the email");    
}