生日电子邮件,空白行和错误日期

时间:2018-05-13 15:11:29

标签: google-apps-script google-sheets timezone gsuite

我有一张包含姓名,电子邮件地址和生日列表的Google工作表。内容看起来像这样:

--------------------------------------------
| Name      | email        | Birthday      |
--------------------------------------------
| John Doe  | john@doe.com | 2018-05-13    |
| Jane Doe  | jane@doe.com | 2018-05-12    |

生日列中的日期正在通过Google工作表作为日期进行验证,并且我已使用datepicker输入这些日期。
我接下来要做的是在适当的生日发送电子邮件给该人,但我遇到了一些问题。
这是代码,我将解释以下问题:

var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;  // First row of data to process
var numRows = 1000;   // Number of rows to process
// Fetch the range of cells B2:B1000
var dataRange = sheet.getRange(startRow, 1, numRows, 1000)
// Fetch values for each row in the Range.
var data = dataRange.getValues();

function sendBirthdayEmails() {
  for (i in data) {
    var row = data[i];
    var startday = Utilities.formatDate(row[2], "UTC+2", "MM-dd"); //Store birthday without year
    var today = Utilities.formatDate(new Date(), "UTC+2", "MM-dd"); //Store current date and remove year
    if (today == startday) { //Evaluate if today is a birthday
      var emailAddress = row[1]; // gather the email address
      var message = "Woop woop, " + row[0] + "!<br>Today is your " + (Utilities.formatDate(new Date(), "UTC+1", "yyyy") - Utilities.formatDate(row[2], "UTC+1", "yyyy")) + " year(s) birthday!"; // Create the email message
      var subject = "Your birthday!"; //Set email subject
      //MailApp.sendEmail(emailAddress, subject, message, {htmlBody: message, replyTo: "birthday@example.com", name: "Birthday wishes", bcc: "myself@exmaple.com"}); //Invoke sending the email
    }
  }
}

我确信有更多顺畅的方式来处理这些事情,如果有,请告诉我。然而,我主要遇到两个问题:
1.由于我无法解释的原因,从生日列的日期评估到前一天的22:00。这听起来像是时区问题,因为我目前处于UTC + 2(CEST)。但是我该如何解决呢? 2.脚本在处理空行/单元格时出现问题,并在处理时抛出错误,处理此问题的正确方法是什么?我假设在获取第2行到第1000行时我正在做的事情可以用更好的方式完成吗?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我查看了您的数据并复制了错误:

我有一个包含“2018-05-13”的单元格。该列格式为日期,数据验证设置为日期。电子表格设置表示时区为GMT,脚本属性表示时区为GMT。

var value = SpreadsheetApp.getActiveSheet().getActiveCell();
Utilities.formatDate(value, "GMT", "MM-dd);

这将返回“05-12”错误1天。

大量的挖掘表明这是solution

Utilities.formatDate(value, Session.getScriptTimeZone(), "MM-dd");

返回正确的值。

Session.getScriptTimeZone()为我返回值“Europe / London”,必须考虑夏令时并导致Utilities.formatDate的行为不同。

相关问题