概要
GAS (Google Apps Script) のトリガーは隔週実行に対応していない。
なので、隔週判定を自前で実装してみる。
考え方
- 「基準日」と「判定日」を引数で渡す
- 「基準日」と「判定日」の経過時間を算出する
- 経過時間を一週間の経過時間で割る
- 結果が偶数であれば、「判定日」は「基準日」から見て隔週日であると判定する
実装
// base: 基準日, target: 判定日 const isBiweeklyDay = (base: Date, target: Date) : boolean => { // 日付以下を切り捨て const baseDate = new Date(base.getFullYear(), base.getMonth(), base.getDate()) const targetDate = new Date(target.getFullYear(), target.getMonth(), target.getDate()) if (baseDate > targetDate) { // target の方が過去 return false } // 経過時間 const passTime = targetDate.getTime() - baseDate.getTime() // 経過時間を一週間で割って、偶数なら隔週 const weekTimes = 604800000 return (passTime / twoWeekTimes) % 2 === 0 }
テスト
jest で書いたサンプル
describe('基準日が 2020-01-01 の場合' => { // month index が 0 始まりなのは分かりにくいので const JANUARY = 0 const baseDate = new Date(2020, JANUARY, 1) test('2020-01-08 は false', () => { expect(isBiweeklyDay(baseDate, new Date(2020, JANUARY, 7))).toBeFalsy() }) test('2020-01-15 は true', () => { expect(isBiweeklyDay(baseDate, new Date(2020, JANUARY, 15))).toBeTruthy() }) })