Google script to create all-day calendar entries - google-apps-script

Apologies if this has been covered but I am trying to write a script for a google form that when completed will send 'events' to my google calendar. I want these events to be all-day events but the closest I could get to making that work was the below but I still get the time 00:00 on it.. Can anyone help?
///this is the ID of the calendar to add the event to, this is found on the calendar settings page of the calendar in question
var calendarId = "bj8vckkvvhnq4ujr2sb914n03c#group.calendar.google.com";
//below are the column ids of that represents the values used in the spreadsheet (these are non zero indexed)
var startDtId = 4;
var endDtId = 5;
var titleId = 2;
var descId = 3;
var formTimeStampId = 1;
function getLatestAndSubmitToCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var startDt = sheet.getRange(lr,startDtId,1,1).getValue();
//set to first hour and minute of the day.
startDt.setHours(0);
startDt.setMinutes(00);
var endDt = sheet.getRange(lr,endDtId,1,1).getValue();
//set endDt to last hour and minute of the day
endDt.setHours(23);
endDt.setMinutes(59);
var subOn = "Submitted on :"+sheet.getRange(lr,formTimeStampId,1,1).getValue();
var desc = "Added by :"+sheet.getRange(lr,descId,1,1).getValue()+"\n"+subOn;
var title = sheet.getRange(lr,titleId,1,1).getValue()
createEvent(calendarId,title,startDt,endDt,desc);
}​
function createEvent(calendarId,title,startDt,endDt,desc) {
var cal = CalendarApp.getCalendarById(calendarId);
var start = new Date(startDt);
var end = new Date(endDt);
var loc = '';
var event = cal.createEvent(title, start, end, {
description : desc,
location : loc
});
};

There is a different function "createAllDayEvent" used to create all day events.
https://developers.google.com/apps-script/reference/calendar/calendar#createAllDayEvent(String,Date,Object)

Related

Get events from multiple calendars in Google Apps Script

I'm posting after having read different posts here in SO, and still, I didn't manage to solve my problem.
What I'm trying to do is basically to retrieve from Google Calendars the events from different calendars and have them listed in an excel file.
The script below correctly gets the events from the first calendar, but not from the others. From the others, I basically get an empty array.
Here is the code I'm working with:
function getEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var sheetsoptions = ss.getSheetByName("Options");
var start_time = sheet.getRange("A2").getValue();
var end_time = sheet.getRange("B2").getValue();
// var id_cal = sheet.getRange("C2").getValue();
var id_cal = sheetsoptions.getRange("A5:A6").getValues();
var arrayLength = id_cal.length;
var cell_events = 5;
for (var j = 0; j < arrayLength; j++) {
if (id_cal[j] == ""){
break;
}
else{
var cal = CalendarApp.getCalendarById(id_cal[j]);
var events = cal.getEvents(new Date(start_time), new Date(end_time));
for (var i = 0;i<events.length;i++){
var title = events[i].getTitle();
var start_time = events[i].getStartTime();
var end_time = events[i].getEndTime();
var loc = events[i].getLocation();
var des = events[i].getDescription();
var vis = events[i].getVisibility();
sheet.getRange(cell_events,1).setValue(title);
sheet.getRange(cell_events,2).setValue(start_time);
sheet.getRange(cell_events,3).setValue(end_time);
sheet.getRange(cell_events,4).setValue(loc);
sheet.getRange(cell_events,5).setValue(des);
sheet.getRange(cell_events,6).setValue(vis);
cell_events++;
}
}
}
Logger.log("Events have been added to the Spreadsheet");
}
Thanks in advance for your help.
Luca
I think you just had a small issue with your calid being a 2d array. Try this, it's almost the same thing that you had, written a little differently.
function getEvents() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var sheetsoptions = ss.getSheetByName("Options");
var start_time = sheet.getRange("A2").getValue();
var end_time = sheet.getRange("B2").getValue();
var calid = sheetsoptions.getRange("A5:A6").getValues().flat().filter(id => id);//test for truthiness
var row = 5;
calid.forEach(id => {
var cal = CalendarApp.getCalendarById(id);
var events = cal.getEvents(new Date(start_time), new Date(end_time));
events.forEach(ev => {
var title = ev.getTitle();
var start_time = ev.getStartTime();
var end_time = ev.getEndTime();
var loc = ev.getLocation();
var des = ev.getDescription();
var vis = ev.getVisibility();
sheet.getRange(row++, 1, 1, 6).setValues([[title, start_time, end_time, loc, des, vis]]);//this should save some time writing all five columns at the same time
});
});
Logger.log("Events have been added to the Spreadsheet");
}
Issue:
You are using the same variables for minimum and maximum dates when listing calendar events and for getting the start and end time of each event (start_time, end_time).
Because of this, after the first calendar iteration, start_time and end_time are not the times defined in cells A2 and B2, but the start and end times of the last event in the first calendar.
Solution:
Update one of the two sets of variables so there's no confusion. For example:
var event_start_time = events[i].getStartTime();
var event_end_time = events[i].getEndTime();
// ...
sheet.getRange(cell_events,2).setValue(event_start_time);
sheet.getRange(cell_events,3).setValue(event_end_time);
Note:
Consider using setValues to write all event values at once instead of setValue, in order to minimize calls to Sheets service and improve efficiency (see Use batch operations).

Script that create an event in a calendar. I have a 50min difference between the google sheet and the calendar

I'm using this amazing script to create an event from a google sheet.
It's working well but the event is created with a 50min difference between the start date in my sheet. I can't figure this out.
For example
Date Title Start Time End Time Location Description Type Recurring
05.04.2022 Test 06:40:00 07:10:00 Sion test
will create an event with a starting hour of 7:30!
Is it about a time zone difference?
// Date | Title | Start Time | End Time | Location | Description | Type | Recurring | EventID
function exportEventsAvecferie() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Evénements récurents - Avec fériés");
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "ID#group.calendar.google.com"; //CalendarApp.getDefaultCalendar().getId();// use default claendar for tests
var cal = CalendarApp.getCalendarById(calId);
for (i in data) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[0]); // First column
var title = row[1]; // Second column
var tstart = setTimeToDate(date,row[2]);
var tstop = setTimeToDate(date,row[3]);
Logger.log('date = '+date+'tstart = '+tstart+' tstop = '+tstop);
var loc = row[4];
var desc = row[5];
var type = row[6];
var times = row[7]
var id = row[8];
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
event.setTitle('got you');
}catch(e){
var newEvent = cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
row[8] = newEvent.getId(); // Update the data array with event ID
Logger.log('event created');
var event = cal.getEventSeriesById(row[8]);
}
event.setTitle(title);
event.setDescription(desc);
event.setLocation(loc);
if(type=='M'){
var recurrence = CalendarApp.newRecurrence().addMonthlyRule().times(times);
event.setRecurrence(recurrence, tstart, tstop);
}else if(type=='S'){
var recurrence = CalendarApp.newRecurrence().addWeeklyRule().times(times)
event.setRecurrence(recurrence, tstart, tstop);
}
data[i] = row ;
}
range.setValues(data)
}
function setTimeToDate(date,time){
var t = new Date(time);
var hour = t.getHours();
var min = t.getMinutes();
var sec = t.getSeconds();
var dateMod = new Date(date.setHours(hour,min,sec,0))
return dateMod;
}
I was able to reproduce and to fix the problem. To make this code work you need to synchronize the time zones in:
Spreadsheet: File > Settings > Time Zone
Script Editor: Project Settings > Time Zone
Calendar: Settings > Time Zone
As soon as I set identical time zone (GMT+01:00 Paris, for example) in these three places the script starts work fine.
Probably there is a way to calculate the difference between these time zones and change the time of the event. Something like this: https://stackoverflow.com/a/35691298/14265469 (not for faint hearted, though)

Google Calendar Event ID Created Can't Find Event Listed -- App Script/Sheets

I have a script which has been running for almost 2 years. I update the sheet with dates and either the event is deleted/created or a new one is created.
This last time I went through and added my dates its normal it populates the sheet cell with the event id and I am on my merry way -- however when I go to the calendar nothing shows up for that date/time.
Is there something I am missing like a new permission -- there are no errors thrown -- nothing in the logs. I have an event id but I dont know how to check what is showing up as I cannot see it on the calendar -- Is there a way to check the event id and see what it contains.
The sheet (I separated with pipes)
Subject|Start Date|Start Time|End Date|End Time|All day event|Meeting Organizer|Description|Location|Reminder Date|Reminder Time|Show time as|Event ID|Status
Survey Edit: Science of HC Delivery|08/07/2017|12:00:00 AM|8/7/2017|12:00:00 PM|TRUE|Seamore Butz|||8/7/2017|9:00:00 AM|3 sg5a7jsakgbj8g5rejeos15lhc#google.com|y
function pushToCalendar()
{
//spreadsheet variables
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
/*
getRange (row,column,optNumRows,optNumColumns)
row --- int --- top row of the range
column --- int--- leftmost column of the range
optNumRows --- int --- number of rows in the range.
optNumColumns --- int --- number of columns in the range
*/
var range = sheet.getRange(2,1,lastRow,13);
var values = range.getValues();
//calendar variables
// xxxxxxxxxxxxxxxxxxxxxxxxxx#group.calendar.google.com
var calendar = CalendarApp.getCalendarById('xxxxxxxxxxxxxxxxxxxxx#group.calendar.google.com')
var numValues = 0;
for (var i = 0; i < values.length; i++)
{
//check to see if name and type are filled out - date is left off because length is "undefined"
if (values[i][0].length > 0)
{
//check if it's been entered before
if (values[i][13] == undefined)
{
//create event https://developers.google.com/apps-script/class_calendarapp#createEvent
var newEventTitle = values[i][0];
Logger.log(newEventTitle);
var dateStart = values[i][1];
var timeStart = values[i][2];
var dateFinish = values[i][3];
var timeFinish = values[i][4];
var startDateTime = new Date(dateStart+" "+timeStart);
startDateTime.setDate(startDateTime.getDate());
startDateTime.setMonth(startDateTime.getMonth());
startDateTime.setYear(startDateTime.getYear());
startDateTime.setTime(startDateTime.getTime());
var stopDateTime = new Date(dateFinish+" "+timeFinish);
stopDateTime.setDate(stopDateTime.getDate());
stopDateTime.setMonth(stopDateTime.getMonth());
stopDateTime.setYear(stopDateTime.getYear());
stopDateTime.setTime(stopDateTime.getTime());
var description = (values[i][7] == '' ? 'Test Description '+i : values[i][7]);
var location = (values[i][8] == '' ? 'Test Location '+i : values[i][8]);
Logger.log(description);
Logger.log(location);
//var newEvent = calendar.createAllDayEvent(newEventTitle, values[i][1]);
var newEvent = calendar.createEvent(newEventTitle, startDateTime, stopDateTime, {description:description,location:location});
//get ID
var newEventId = newEvent.getId();
//mark as entered, enter ID
sheet.getRange(i+2,14).setValue('y');
sheet.getRange(i+2,13).setValue(newEventId);
// in case of larger sheets we need to sleep the process
Utilities.sleep(1000);
}
else if (values[i][14] == 'u')
{
// can update event so need to delete and create again
// delete event
var event = calendar.getEventSeriesById(values[i][9]);
event.deleteEventSeries();
//create event
var newEventTitle = values[i][0];
//create event https://developers.google.com/apps-script/class_calendarapp#createEvent
var newEventTitle = values[i][0];
var dateStart = values[i][1];
var timeStart = values[i][2];
var dateFinish = values[i][3];
var timeFinish = values[i][4];
var startDateTime = new Date(dateStart+" "+timeStart);
startDateTime.setDate(startDateTime.getDate());
startDateTime.setMonth(startDateTime.getMonth());
startDateTime.setYear(startDateTime.getYear());
startDateTime.setTime(startDateTime.getTime());
var stopDateTime = new Date(dateFinish+" "+timeFinish);
stopDateTime.setDate(stopDateTime.getDate());
stopDateTime.setMonth(stopDateTime.getMonth());
stopDateTime.setYear(stopDateTime.getYear());
stopDateTime.setTime(stopDateTime.getTime());
var description = (values[i][7] == undefined ? 'Test Description '+i : values[i][7]);
var location = (values[i][8] == undefined ? 'Test Location '+i : values[i][8]);
//var newEvent = calendar.createAllDayEvent(newEventTitle, values[i][1]);
var newEvent = calendar.createEvent(newEventTitle, startDateTime, stopDateTime, {description:description,location:location});
//get ID
var newEventId = newEvent.getId();
//mark as entered, enter ID
sheet.getRange(i+2,14).setValue('y');
sheet.getRange(i+2,13).setValue(newEventId);
// in case of larger sheets we need to sleep the process
Utilities.sleep(1000);
}
else
{
Logger.log('I am groot');
sheet.getRange(i+2,14).setValue('y');
}
}
numValues++;
}
}
function onOpen()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
menuEntries.push({name: "Grades & Evals", functionName: "pushToCalendar"});
sheet.addMenu("Sync to Academic Master", menuEntries);
}
I found the issue finally .. one of those tiny issue found after logging more and googling the Invalid Date response.
On line 16 this
var values = range.getValues();
needed to change to this
var values = range.getDisplayValues();
So thanks :)

Cannot create an all day event series into google calendar, from google forms

I have been trying for days now, reading other posts, playing with other scripts that have been close to the same purpose and nothing works. I am trying to make a script that will take information from a web based google form, along with a month/day and turn it into a re-occuring event in the Calendar.
It is finally posting to the Calendar NOW but every event comes up undefined under December 31, 2015 - with no further information, altho at least it is reoccurring.
Any help would be greatly appreciated as I try to understand this coding and how to do it. Thank you!
//this is the ID of the calendar to add the event to, this is found on the calendar settings page of the calendar in question
var calendarId = "id#group.calendar.google.com";
//below are the column ids of that represents the values used in the spreadsheet (these are non zero indexed)
var startDtId = 5;
var endDtId = 5;
var titleId = 2;
var descId = 3;
var formTimeStampId = 1;
function getLatestAndSubmitToCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var startDt = sheet.getRange(lr,startDtId,1,1).getValue();
//set to first hour and minute of the day.
// startDt.setHours(0);
// startDt.setMinutes(00);
var endDt = sheet.getRange(lr,endDtId,1,1).getValue();
//set endDt to last hour and minute of the day
// endDt.setHours(23);
// endDt.setMinutes(59);
// var subOn = "Submitted on :"+sheet.getRange(lr,formTimeStampId,1,1).getValue();
var desc = sheet.getRange(lr,descId,1,1).getValue();
var title = sheet.getRange(lr,titleId,1,1).getValue();
createAllDayEvent(calendarId,title,startDt,endDt,recurrence,loc,desc);
}​
function createAllDayEventSeries(calendarId,title,startDt,endDt,recurrence,loc,desc) {
var cal = CalendarApp.getCalendarById('id#group.calendar.google.com');
var start = new Date(startDt);
var end = new Date(endDt);
var loc = descId;
var desc = "Happy Birthday "+titleId+" of "+descId;
// Creates a rule that recurs every week for ten weeks.
var recurrence = CalendarApp.newRecurrence().addYearlyRule();
var event = cal.createAllDayEventSeries(title, start, recurrence, {
description : desc,
location : loc
});
};
I created a form and tested with the following code:
// Column data constants
var nameCol = 2;
var birthdayCol = 3;
var descriptionCol = 4;
var locationCol = 4;
var calendarId = '[id]#group.calendar.google.com';
/* Send Confirmation Email with Google Forms */
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("CreateCalendarEvent")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function createEvent() {
var ss = SpreadsheetApp.getActiveSheet();
var rows = ss.getDataRange();
var lr = rows.getLastRow();
var start = ss.getRange(lr,birthdayCol,1,1).getValue();
start.setHours(0);
start.setMinutes(00);
var title = ss.getRange(lr,nameCol,1,1).getValue() + " Birthday";
var desc = ss.getRange(lr,descriptionCol,1,1).getValue();
var loc = ss.getRange(lr,locationCol,1,1).getValue();
var recurrence = CalendarApp.newRecurrence().addYearlyRule();
Logger.log("accessing calendar");
var externalCalendar = CalendarApp.getCalendarById(calendarId);
externalCalendar.createAllDayEventSeries(title, start, recurrence, {
description : desc,
location : loc
});
}
function getRelativeDate(daysOffset, hour) {
var date = new Date();
date.setDate(date.getDate() + daysOffset);
date.setHours(hour);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
function CreateCalendarEvent(e) {
try {
Logger.log("creating event");
createEvent();
} catch (e) {
Logger.log(e.toString());
}
}
This sets a trigger function when the form is submitted, make sure that you change the value of the calendar id to the one provided by your calendar.

Create recurring Google Calendar events from Google Sheets only on weekdays

The following code below works perfectly. However, I now need to have recurring events to appear only during the weekdays (M-F).
If for example I set up a recurring meeting on 9/2/2014, future meetings will eventually fall on a weekend.
How can these recurring meetings only show up on weekdays?
For example, if meeting falls on a Saturday, move it to the day before (Friday). On the other hand, if meeting falls on a Sunday, move it to the day after (Monday).
is this possible?
I have tried using the CalendarApp.Weekday.MONDAY, etc...function but it ends up writing over the .addMonthlyRule() function from the code...
// Date | Title | Start Time | End Time | Location | Description | Recurring (months) | EventID
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Calendar Actions", entries);
};
/*** Export events from spreadsheet to calendar */
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "airliquide.com_ro3r20vk2rhm506fr2toq4vh5c#group.calendar.google.com";
var cal = CalendarApp.getCalendarById(calId);
for (i in data) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[0]); // First column
var title = row[1]; // Second column
var tstart = setTimeToDate(date,row[2]);
var tstop = setTimeToDate(date,row[3]);
Logger.log('date = '+date+'tstart = '+tstart+' tstop = '+tstop);
var loc = row[4];
var desc = row[5];
var times = row[6]
var id = row[7];
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
event.setTitle('got you');// this is to "force error" if the event does not exist, il will never show for real ;-)
}catch(e){
var newEvent = cal.createEvent(title, tstart, tstop, {description:desc,location:loc}); // create a "normal" event
row[7] = newEvent.getId(); // Update the data array with event ID
Logger.log('event created');// while debugging
var event = cal.getEventSeriesById(row[7]);// make it an event Serie
}
event.setTitle(title);
event.setDescription(desc);
event.setLocation(loc);
var recurrence = CalendarApp.newRecurrence().addMonthlyRule().interval(times)
//.onlyOnWeekdays(
//[CalendarApp.Weekday.MONDAY, CalendarApp.Weekday.TUESDAY, CalendarApp.Weekday.WEDNESDAY, CalendarApp.Weekday.THURSDAY, CalendarApp.Weekday.FRIDAY]);
event.setRecurrence(recurrence, tstart, tstop);// we need to keep start and stop otherwise it becomes an AllDayEvent if only start is used
}
range.setValues(data);
}
function setTimeToDate(date,time){
var t = new Date(time);
var hour = t.getHours();
var min = t.getMinutes();
var sec = t.getSeconds();
var dateMod = new Date(date.setHours(hour,min,sec,0))
return dateMod;
}
You can get the day of the week by using the following:
var d = new Date();
var n = d.getDay();
Sunday is 0, Monday is 1 etc.