home about terms twitter

(GAS) Deletion of the events in a period for Google Calendar

date: 2021-04-28 | mod: 2021-04-28

Introduction

Google Calendar can be linked with GAS (Google Apps Script) to change, add, and delete appointments (official documentation).

With calendar appointments, there is a way to add the events you want to add sequentially. On the other hand, there are some situations you want to delete existing events.

Therefore, this article describes how to delete the events within a certain period of time from Google Calendar using GAS.

Method

Insert the following code into the function in the .gs file that manipulates the calendar.

You can get the id of the calender from “Settings”, “Calendar ID”, or from the URL you accessed.

Insert the obtained id into your_calender_id.

var calender = CalendarApp.getCalendarById('your_calender_id');

// Get the deletion start date
var delStartDate = new Date('January 1, 2021');
// get the end date of deletion
var delEndDate = new Date('January 1, 2022');

var events = calender.getEvents(delStartDate, delEndDate);
for (var i in events) {
    // sleep
    Utilities.sleep(1000)

    var event = events[i];
    event.deleteEvent();
}

You will get the events of the period as a list. Then it will execute deleteEvent() for that number of events.

This will delete the events scheduled for January 1, 2021 to January 1, 2022.

Note that if you edit a lot of events in a short period of time, you will get `Exception: You have been creating or deleting too many calendars or calendar events in a short time.

To avoid the error you need to add Utilities.sleep(1000) in the middle of the loop. in the middle of the loop. This will cause it to sleep for 1000 milliseconds = 1 second.

Also, if you have a lot of events to create, the calendar may be limited in use for several hours or more.

For more information about calendar usage limits, please refer to “Google Wordspace Administrator Help - Avoid Calendar use limits”.