【GAS】日本の休日・祝日をカレンダーから判定する
やりたいこと
GASを定期実行するにあたって、休日・祝日には実行されないようにしたい。
トリガーでは特定の曜日を除外することすらできないので、コード上で判定する必要がある。
解決法
clasp環境(TypeScript)の場合
schedule.ts
を作成し、そこに判定ロジックを書く。
namespace Schedule { export const isWorkingDay = () => !(isWeekend() || isHoliday());
/** * 休日か */ const isWeekend = () => { const day = new Date().getDay(); return day === 6 || day === 0; };
/** * 祝日か */ const isHoliday = () => { const calendars = CalendarApp.getCalendarsByName("日本の祝日"); return calendars[0].getEventsForDay(new Date()).length > 0; };}
- 休日は曜日から判定
- 祝日はGoogleカレンダーに標準で入っている「日本の祝日」から判定
const main = () => { if (!Schedule.isWorkingDay()) return;
// 実行したい処理};
これで休日・祝日を除外して定期実行が可能になった。
ブラウザ環境(gs)の場合
"use strict";var Schedule;(function (Schedule) { Schedule.isWorkingDay = () => !(isWeekend() || isHoliday()); /** * 休日か */ const isWeekend = () => { const day = new Date().getDay(); return day === 6 || day === 0; }; /** * 祝日か */ const isHoliday = () => { const calendars = CalendarApp.getCalendarsByName("日本の祝日"); return calendars[0].getEventsForDay(new Date()).length > 0; };})(Schedule || (Schedule = {}));
参考