While writing the question, I thought I'd have a go at it with ChatGPT. And somehow it worked!
Here's the code:
function getTotalEventTime() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var searchString = "Your Predefined String"; // Replace with your predefined string
var startDate = new Date("2023-01-01"); // Replace with your desired start date
var endDate = new Date("2023-12-31"); // Replace with your desired end date
var email = "[email protected]"; // Replace with the email address you want to calculate the total time for
var calendar = CalendarApp.getCalendarById(email);
if (!calendar) {
Logger.log("Invalid email address or insufficient permission.");
return;
}
var events = calendar.getEvents(startDate, endDate);
var totalEventTime = 0;
for (var i = 0; i < events.length; i++) {
var event = events[i];
if (event.getTitle().startsWith(searchString) && event.getMyStatus() !== CalendarApp.GuestStatus.DECLINED) {
var eventDuration = event.getEndTime() - event.getStartTime();
totalEventTime += eventDuration;
}
}
// Convert milliseconds to hours
var totalEventHours = totalEventTime / (1000 * 60 * 60);
// Write the total event time to the sheet
sheet.getRange("A1").setValue("Total Event Time:");
sheet.getRange("B1").setValue(totalEventHours);
}
And the instructions:
Here's how you can use this script:
- Open your Google Sheets document.
- Click on "Extensions" in the top menu.
- Select "Apps Script" from the dropdown menu. This will open
the Apps Script editor in a new tab.
- Delete any existing code in the editor. Copy and paste the above script into the editor. Modify the
searchString
, startDate
, endDate
, email
variables to fit your requirements. The searchString
should be replaced with your predefined string, and the startDate
and endDate
should be set to the desired period you want to retrieve events from. email
should be set to the email address for which you want to calculate the total time.
- Save the script by clicking on the floppy disk icon or by pressing Ctrl + S.
- Close the Apps Script editor tab. In your Google Sheets document, you can now run the script by clicking on "Extensions" in the top menu, selecting "Apps Script," and choosing the "getTotalEventTime" function.
- List item
The total event time will be displayed in cell B1 of the active sheet. Remember to configure the predefined string, start date, end date, and email address according to your needs. The first time you need to give permissions for running the script and accessing your calendar.
PS. Declined events are not included in the total event time.