我的 GAS 脚本无法在没有任何错误的情况下创建事件

My GAS script can't create events without any errors

问题

我想制作一个从特定电子邮件创建事件的脚本,我做到了。当我运行它时,它无一例外地完成了。但是我的实际日历上没有出现任何事件。 我认为我的代码没有错。我想知道是否需要配置一些身份验证设置来创建事件。 如果你能教我解决这个问题的方法,我将不胜感激。

我试过的

代码和控制台日志

代码和输出如下。

function myFunction() {
 var event = CalendarApp.getDefaultCalendar().createEvent(
   "test", 
   new Date("2021", "02", "20", "10", "05"),
   new Date("2021", "02", "28", "10", "30"));
 console.log('Event ID: ' + event.getTitle() + ' is created');
}
5:52:52 PM  Notice  Execution started
5:54:17 PM  Info    Event ID: test is created
5:52:53 PM  Notice  Execution completed

解释/问题

您正在尝试创建从 2 月 20 日到 2 月 28 日的活动。

  • 问题是您的日期对象定义不正确。

你也可以阅读 here:

JavaScript counts months from 0 to 11. January is 0. December is 11

因此,对于二月,new Date 对象中的第二个参数应该是 1 而不是 2。或者换句话说,您的代码现在正在为三月创建事件。

如果你去三月份,当你尝试多次执行代码时,你现在可能已经创建了多个事件。

解决方案:

变化:

new Date("2021", "02", "20", "10", "05"),
new Date("2021", "02", "28", "10", "30")

收件人:

new Date("2021", "01", "20", "10", "05"),
new Date("2021", "01", "28", "10", "30")

参数不一定要是字符串,也可以是数字(整数):

function myFunction() {
 var event = CalendarApp.getDefaultCalendar().createEvent(
   "test", 
   new Date(2021, 01, 20, 10, 05),
   new Date(2021, 01, 28, 10, 30));
 console.log('Event ID: ' + event.getTitle() + ' is created');
}

奖金信息:

要查看您是否拥有正确的日期对象,您还可以 console.log 您的日期。例如,您的代码给出了三月的日期:

function myFunction() {
  console.log(new Date(2021, 02, 20, 10, 05));
  console.log(new Date(2021, 02, 28, 10, 30));
}

哪个日志: