Skip to content

Instantly share code, notes, and snippets.

@shubham1172
Created June 26, 2020 10:19
Show Gist options
  • Save shubham1172/35a3d8ffac219717154ffe8e9198a6c9 to your computer and use it in GitHub Desktop.
Save shubham1172/35a3d8ffac219717154ffe8e9198a6c9 to your computer and use it in GitHub Desktop.
CalendarSyncService
// run this script as a trigger for your events spreadsheet to sync all the events with google calendar
function myFunction() {
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getDataRange().sort(1)
Logger.log("Fetching calendar data...");
// TODO: replace calendarId with actual id
var cal = CalendarApp.getCalendarById(calendarId);
var titles = fetchCalendarTitles(cal);
Logger.log("Fetching sheet data...");
var data = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getDataRange().getValues();
for (row in data) {
var title = data[row][0] + "'s birthday";
if (titles.indexOf(title) == -1) {
// insert the entry in calendar
var event = cal.createAllDayEventSeries(title, formatDate(data[row][1]), CalendarApp.newRecurrence().addYearlyRule())
Logger.log("Adding new event: " + event.getTitle() + " (id: " + event.getId() + ")");
}
}
Logger.log("Synchronization complete!")
}
function fetchCalendarTitles(cal) {
thisYear = new Date().getYear() + 1900;
startDate = new Date(thisYear+'-1-1');
endDate = new Date(thisYear+'-12-31');
var events = cal.getEvents(startDate, endDate);
titles = []
for (e in events) {
titles.push(events[e].getTitle());
}
return titles;
}
// convert dd/mm to date object
function formatDate(dt) {
d = dt.split("/")[0];
m = dt.split("/")[1];
y = new Date().getYear() + 1900;
return new Date(y+"-"+m+"-"+d);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment