Skip to content

Instantly share code, notes, and snippets.

@afomi
Created May 31, 2024 21:44
Show Gist options
  • Save afomi/805de9eaab4cb57d9bf949a34243d7c4 to your computer and use it in GitHub Desktop.
Save afomi/805de9eaab4cb57d9bf949a34243d7c4 to your computer and use it in GitHub Desktop.
list_times_in_google_calendar - google app script
// To list available Google Calendar times as text
// Create this function at https://script.google.com/
// Run the app and authorize it access Google Calendar
//
function listAvailableTimes() {
// Define the calendar and the time period to check for availability
var calendarId = 'primary'; // Use 'primary' for the primary calendar or the calendar ID for a specific calendar
var startTime = new Date(); // Start from the current time
var endTime = new Date();
endTime.setDate(startTime.getDate() + 7); // Check for the next 7 days
// Fetch events within the specified time range
var events = CalendarApp.getCalendarById(calendarId).getEvents(startTime, endTime);
// Define working hours (e.g., 9 AM to 5 PM)
var workStartHour = 9;
var workEndHour = 17;
var availableTimes = [];
var currentTime = new Date(startTime);
currentTime.setHours(workStartHour, 0, 0, 0); // Start from the beginning of the working day
while (currentTime < endTime) {
var isFree = true;
for (var i = 0; i < events.length; i++) {
var event = events[i];
if (event.isAllDayEvent() || (event.getStartTime() <= currentTime && event.getEndTime() > currentTime)) {
isFree = false;
currentTime = event.getEndTime();
break;
}
}
if (isFree) {
var endTimeSlot = new Date(currentTime);
endTimeSlot.setMinutes(currentTime.getMinutes() + 30); // Check for 30-minute slots
if (endTimeSlot.getHours() > workEndHour || endTimeSlot > endTime) {
currentTime.setHours(workStartHour, 0, 0, 0); // Move to the next day
currentTime.setDate(currentTime.getDate() + 1);
continue;
}
availableTimes.push(formatTimeSlot(currentTime, endTimeSlot));
currentTime.setMinutes(currentTime.getMinutes() + 30);
}
}
// Log the available times (or you can do something else with them, like send an email)
Logger.log(availableTimes.join('\n'));
}
function formatTimeSlot(startTime, endTime) {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var startDay = days[startTime.getDay()];
var startHours = startTime.getHours();
var startMinutes = startTime.getMinutes();
var endHours = endTime.getHours();
var endMinutes = endTime.getMinutes();
return Utilities.formatString('%02d:%02d %s - %02d:%02d %s %s',
startHours, startMinutes, (startHours >= 12 ? 'PM' : 'AM'),
endHours, endMinutes, (endHours >= 12 ? 'PM' : 'AM'),
startDay);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment