Google Apps Script休假日历:如何排除非全天事件?
Google日历脚本判断全天事件的问题解决
问题描述
自定义Google休假日历脚本时,尝试阻止非全天事件同步到共享日历,调用event.isAllDayEvent()时出现错误:
TypeError: event.isAllDayEvent is not a function
问题原因
代码中通过Calendar.Events.list()获取的事件是Google Calendar API返回的普通JSON对象,并非Apps Script内置的CalendarEvent类实例。这两种对象的属性和方法完全不同,isAllDayEvent()是CalendarEvent类的专属方法,API返回的JSON对象没有这个方法。
解决方案
Calendar API返回的事件对象中,全天事件会包含start.date属性(而非带时间的start.dateTime),同时end.date也会存在。直接通过检查start.date是否存在,就能判断是否为全天事件:
- 存在
start.date→ 全天事件 - 仅存在
start.dateTime→ 非全天事件
修改后的代码
将原代码中判断全天事件的部分替换,完整的shouldImportEvent函数如下(注意原函数名拼写错误:shoudImportEvent修正为shouldImportEvent):
/** * 判断给定事件是否应导入到共享团队日历 * @param {Session.User} user 参与事件的用户 * @param {string} keyword 搜索的关键词 * @param {Object} event 待判断的事件(Calendar API返回的对象) * @return {boolean} 是否应导入 */ function shouldImportEvent(user, keyword, event) { // 过滤摘要中不包含关键词的事件 if (event.summary.toLowerCase().indexOf(keyword) < 0) { return false; } // 非全天事件不导入:检查start.date是否存在 if (!event.start.date) { return false; } // 如果用户是事件组织者,直接导入 if (!event.organizer || event.organizer.email == user.getEmail()) { return true; } // 只导入用户已接受的事件 if (!event.attendees) return false; let matching = event.attendees.filter(function(attendee) { return attendee.self; }); return matching.length > 0 && matching[0].responseStatus == 'accepted'; }
补充说明
Calendar API返回的事件对象中,时间字段分为两种:
- 全天事件:使用
start.date和end.date,格式为YYYY-MM-DD - 非全天事件:使用
start.dateTime和end.dateTime,格式为带时区的RFC3339字符串
只需通过event.start.date是否存在即可准确判断是否为全天事件,无需额外处理时区问题。
内容的提问来源于stack exchange,提问作者Will Mearns
相关产品推荐
相关产品推荐

