My GAS script can't create events without any errors

Viewed 48

Problem

I want to make a script that creates events from specific emails, and I made it. When I run it, it was completed without exceptions. But no events appeared on my actual calendar. I think my code is not wrong. I'm wondering if I need to configure some authentication settings to create events. I would appreciate it if you could teach me the way to solve this problem.

What I tried

  • I checked I could read events through GAS.
  • I read emails that I want from GAS.
  • I checked if the default calendar ID is correct, and it was the correct one.

Code and console log

The code and output are below.

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
1 Answers

Explanation / Issue

You are trying to create an event from the 20th of February until the 28th of February.

  • The issue is your date objects are not defined correctly.

As you can also read here:

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

Therefore, for February the second parameter in the new Date object should be 1 and not 2. Or in other words, your code right now creates events for March.

If you go to March you probably have created by now multiple events when you tried to execute the code multiple times.

Solution:

Change:

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

To:

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

The parameters don't have to be strings, you can also use numbers (integers):

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');
}

Bonus Info:

To see if you have the right date object, you can also console.log your date. For example, your code gives dates for March:

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

which logs:

enter image description here

Related