Have you ever planed to execute Google Apps Script only on business day? Send mail only on business day, or process on the weekend except holiday, etc. I thought script to make it.
First, write core script and set trigger to work on weekdays.
Process except Holiday
It means to process only on business day. Get holiday information from Google Calendar.
Add the following code to the first of the process.
1 2 3 4 5 6 7 8 9 |
var currentDate = new Date(); var weekday = currentDate.getDay(); if (weekday == 0 || weekday == 6) { return; } var calendar = CalendarApp.getCalendarById('ja.japanese#holiday@group.v.calendar.google.com'); if (calendar.getEventsForDay(currentDate, {max: 1}).length > 0) { return; } |
It stop the process on Sunday and Saturday, and also on holiday in Japanese holiday calendar, prepared by Google. You can configure the day on which the script works, by setting trigger, too.
It is good to create function that returns bool value.
If you have other special holiday, create special holiday calendar and add some code to check it. Calendar ID which should be passed to getCalendarById
is saw in the page of its calendar.
Process the Beginning of the Week
Process on Monday, but when the day is holiday, process on Tuesday, and so on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var currentDate = new Date(); var weekday = currentDate.getDay(); if (weekday == 0 || weekday == 6) { return; } var calendar = CalendarApp.getCalendarById( 'ja.japanese#holiday@group.v.calendar.google.com'); if (calendar.getEventsForDay(currentDate, {max: 1}).length > 0) { return; } for (var i = weekday - 1; i > 0; --i) { var day = new Date(currentDate.getTime() - i * 1000 * 60 * 60 * 24); if (calendar.getEventsForDay(day, {max: 1}).length == 0) { return; } } |
Process on the Business Weekend
This is the case like the above. Basically weekend is Friday, but when the Friday is holiday, process on the former day.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var currentDate = new Date(); var weekday = currentDate.getDay(); if (weekday == 0 || weekday == 6) { return; } var calendar = CalendarApp.getCalendarById( 'ja.japanese#holiday@group.v.calendar.google.com'); if (calendar.getEventsForDay(currentDate, {max: 1}).length > 0) { return; } for (var i = 5 - weekday; i > 0; --i) { var day = new Date(currentDate.getTime() + i * 1000 * 60 * 60 * 24); if (calendar.getEventsForDay(day, {max: 1}).length == 0) { return; } } |
On the above, I used getEventsForDay
to retrieve holiday information from the calendar, but getEvents
is also available. getEvents
can retrieve schedule for 1 week, so you can reduce the number of API execution.