Skip to content

Instantly share code, notes, and snippets.

@nvanexan
Created September 24, 2021 20:07
Show Gist options
  • Save nvanexan/c05835280108a8a42ccf7f836f6af61b to your computer and use it in GitHub Desktop.
Save nvanexan/c05835280108a8a42ccf7f836f6af61b to your computer and use it in GitHub Desktop.
Google Apps Script for Consolidating Many Calendars into One
const now = new Date();
const thirtyDaysFromNow = new Date(now.getTime() + (30 * 24 * 60 * 60 * 1000));
const sourceCalendarIds = [] // array of ids of calendars you want to consolidate
const targetCalendarId = '' // string of your target calendar id (i.e. the calendar you want to consolidate events to)
const sourceCalendars = sourceCalendarIds.map(id => CalendarApp.getCalendarById(id))
const targetCalendar = CalendarApp.getCalendarById('')
function sync() {
Logger.log('Starting sync...')
// Get existing events from the target calendar
const existingEvents = targetCalendar.getEvents(now, thirtyDaysFromNow)
const existingEventsKeys = new Set(existingEvents.map(e => `${e.getStartTime()}#####${e.getEndTime()}`))
Logger.log('existing events')
Logger.log(existingEventsKeys.size)
// Get the events from all of the source calendars
const sourceEvents = sourceCalendars.reduce((acc, cal) => {
const events = cal.getEvents(now, thirtyDaysFromNow)
return [...acc, ...events]
}, [])
const sourceEventsKeys = new Set(sourceEvents.map(e => `${e.getStartTime()}#####${e.getEndTime()}`))
Logger.log('source events')
Logger.log(sourceEventsKeys.size)
// Determine the events that should be removed from target calendar
const eventsToDeleteKeys = new Set([...existingEventsKeys].filter(x => !sourceEventsKeys.has(x)))
const eventsToDelete = existingEvents.filter(e => eventsToDeleteKeys.has(`${e.getStartTime()}#####${e.getEndTime()}`))
Logger.log('events to delete')
Logger.log(eventsToDeleteKeys.size)
// Determine the events that should be added to the target calendar
const eventsToCreateKeys = new Set([...sourceEventsKeys].filter(x => !existingEventsKeys.has(x)))
Logger.log('events to create')
Logger.log(eventsToCreateKeys.size)
// Delete the events that should be removed from the target calendar
eventsToDelete.forEach((e, i) => {
if (i % 10 === 0) Utilities.sleep(3000) // to deal with throttling of requests by Google
Logger.log(`Deleting outdated event: ${e.getStartTime()}, ${e.getEndTime()}`)
e.deleteEvent()
})
// Create the events that should be added to the target calendar
Array.from(eventsToCreateKeys).forEach((e, i) => {
Logger.log(i)
if (i % 10 === 0) Utilities.sleep(3000) // to deal with throttling of requests by Google
const [start, end] = e.split('#####')
targetCalendar.createEvent('Not available', new Date(start), new Date(end))
Logger.log(`New event created for ${new Date(start)}, ${new Date(end)}`)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment