🙆

GASで毎月最初の営業日に処理を実行したい

2025/03/01に公開

Daily Blogging70日目

たとえば、2025年11月の場合だと
11月1日:土曜日
11月2日:日曜日
11月3日:月曜日(文化の日)
11月4日:火曜日←ここで処理を実行したい!

※トリガーは毎日実行するものとするよ

コード

最終的にこんな感じになりました

function isNoticeDay(today, year, month) {
  // MEMO: 第一営業日に通知
  const firstBusinessDay = getFirstBusinessDay(year, month);

  if (today.toDateString() !== firstBusinessDay.toDateString()) {
    Logger.log("今日は通知しないよ");
    return false;
  }

  return true;
}

function getFirstBusinessDay(year, month) {
  const date = new Date(year, month,1);

  while(date.getDay() === 0 || date.getDay() === 6 || isHoliday(date)) {
    date.setDate(date.getDate() + 1)
  }

  return date;
}

function isHoliday(date) {
  // Googleカレンダーの日本の祝日カレンダーID
  const calendarId = "ja.japanese#holiday@group.v.calendar.google.com";
  const calendar = CalendarApp.getCalendarById(calendarId);

  const events = calendar.getEventsForDay(date);

  return events.length > 0;
}

ポイント

その月の第一営業日かを判断するには情報が二つ必要

  • その月の最初の平日かどうか
  • 祝日かどうか

最初の平日を取得する

平日かどうかはgetDay()を基に判定可能
0: 日曜日
6: 土曜日

0,6でなければ平日ということになるよ

// その月の1日を取得する
const date = new Date(year, month,1);

// 平日になるまでdateを1日ずつ進める
while(date.getDay() === 0 || date.getDay() === 6) {
    date.setDate(date.getDate() + 1)
  }

平日になるまでループしておけば、最初の平日を取得できる。

祝日かどうか

日本の祝日はgoogleカレンダーに元々登録されているのでその情報を利用する。
指定した日付が祝日の場合、eventsにデータが入る。

function isHoliday(date) {
  // Googleカレンダーの日本の祝日カレンダーID
  const calendarId = "ja.japanese#holiday@group.v.calendar.google.com";
  const calendar = CalendarApp.getCalendarById(calendarId);

  const events = calendar.getEventsForDay(date);

  return events.length > 0;
}

Discussion