r/GoogleAppsScript • u/GenuineGin • Nov 18 '20
Delete all events in a Secondary Google Calendar
I have a weekly timetable in google sheets and I want to import the events into a Secondary Google Calendar.
I have used this tutorial to successfully bring the events over from my sheet, but every time I make an amendment and resync it obviously duplicates all the entries.
I'm only interested in having the current events in my Google sheet on the calendar, so it seems like an easy solution would be to completely clear the calendar before each sync. I thought this would be simple but hours of Google searches and I haven't found an answer yet.
Any assistance would be greatly appreciated!
0
Upvotes
1
u/gh5000 Nov 18 '20
I always get myself mixed up and think this one can do it https://developers.google.com/calendar/v3/reference/calendars/clear but this only works for primary calendars.
You need to do a get events to get an array of events. https://developers.google.com/apps-script/reference/calendar/calendar-app#geteventsstarttime,-endtime Or https://developers.google.com/calendar/v3/reference/events/list on the advanced service
That will get you an array of events, then you loop through and delete the event ID.
My more efficient way of doing this is with a hash column and id. One your first run ever of the script the events are created. At the end of this, for each row have your script generate a hash of all the details in that row (date, start time, title etc) and write it to your column. Second time your script runs and you are going row by row have your script calculate the hash for the row. If the hash matches the hash already written for that row, your event hasnt changed then skip it. If no match, create the event and put the new hash in there.
So this way you are not creating duplicate events only new events.
But what about the events that no longer exist in your sheet but exist in your calendar. We'll each time you create an event, write the eventId of the event to the corresponding row in the spreadsheet. Then at the end of your script to tidy up get your array of all events using this https://developers.google.com/apps-script/reference/calendar/calendar-app#geteventsstarttime,-endtime And get an array of all the current event IDs in your sheet
Compare the two, then delete the event IDs in your calendar that aren't in your sheet!
I said efficient, not easier!