Reputation: 107
I want to find the next Good Friday ("Karfreitag"), create a new event in my calendar and extend to the hole holy week.
I found some good examples on SO, and adjusted to:
function copyHoliday() {
var calRebate = CalendarApp.getCalendarById('[email protected]'); // external (rebate periods)
var calHoliday = CalendarApp.getCalendarById('de.christian#[email protected]'); // external (holiday periods)
var searchStart = new Date('2021','0','1');
var searchEnd = new Date(searchStart.getDate() + (365 * 24 * 60 * 60 * 1000));
Logger.log(searchStart ,searchEnd);
var officialKarEvent = calHoliday.getEvents(searchStart,searchEnd,{search: 'Karfreitag'});
var myKarEvent = calRebate.createAllDayEvent('Karwoche',officialKarEvent.getAllDayStartDate()-4,officialKarEvent.getAllDayEndDate()+2);
return(myKarEvent);
}
function main() {
Logger.log(copyHoliday());
}
Failure:
TypeError: Cannot read property 'createAllDayEvent' of null
Somehow my officialKarEvent does not return an event.
Is this because there may be theoretically more than one event in the search, and the script does not know which to process?
Thank You for Your help!
Upvotes: 1
Views: 100
Reputation: 11194
It should only have one event since there are no other events named Karfreitag
. But to be sure, what I did was check if it was the exact title of the event.
Upon checking the supplied calendar, I copied the title of that and then used in my code below.
Also, your subtraction on createAllDayEvent
dates are only modifying in milliseconds. So the safe way to adjust it is via setDate
and getDate
.
function copyHoliday() {
var calendarSource = CalendarApp.getCalendarById('de.christian#[email protected]');
var calendarDestination = CalendarApp.getCalendarById('destination calendar');
var start = new Date('2021','0','1');
// Sometimes, years are not 365 days, so better spell it out
var end = new Date('2021','11','31');
var eventToCopy = calendarSource.getEvents(start, end);
for (var i in eventToCopy){
if (eventToCopy[i].getTitle() == "Karfreitag (regionaler Feiertag)"){
var startDate = eventToCopy[i].getAllDayStartDate();
startDate.setDate(startDate.getDate() - 4)
var endDate = eventToCopy[i].getAllDayEndDate();
endDate.setDate(endDate.getDate() + 2);
calendarDestination.createAllDayEvent("Karwoche", startDate, endDate);
// Exit afterwards
return;
}
}
}
Upvotes: 1