listHolidayDates(year, opts) reads a public holiday calendar with CalendarApp and returns sorted yyyy-MM-dd strings for that year, ready to pass to Add Business Days. {calendarId} defaults to the United States holiday calendar, en.usa#holiday@group.v.calendar.google.com.
When to use
- Building a Holidays tab so due-date formulas skip public holidays
- Refreshing next year's holidays every January
- Any script that already has a list of office closures and needs the public ones too
How to use this snippet
Subscribe to the public calendar in Google Calendar first (Other calendars). getCalendarById returns nothing until that account can see it.
/**
* Return sorted yyyy-MM-dd holiday dates for a year from a public calendar.
* Uses CalendarApp.getCalendarById. opts.calendarId defaults to
* en.usa#holiday@group.v.calendar.google.com. All-day events use each
* civil day from the start date up to (not including) the exclusive end.
* Dates are formatted in the spreadsheet timezone so they match
* addBusinessDays. Throws if the year is not an integer or the calendar
* is not visible to this account.
*
* @param {number} year
* @param {{calendarId?: string}} [opts]
* @return {string[]}
*/
function listHolidayDates(year, opts) {
opts = opts || {};
var y = Number(year);
if (!y || y !== Math.floor(y)) {
throw new Error('listHolidayDates: year must be an integer');
}
var calendarId = String(
opts.calendarId == null || String(opts.calendarId).trim() === ''
? 'en.usa#holiday@group.v.calendar.google.com'
: opts.calendarId
).trim();
var cal = CalendarApp.getCalendarById(calendarId);
if (!cal) {
throw new Error(
'listHolidayDates: calendar not found: ' + calendarId +
'. Subscribe to that public calendar in Google Calendar first (Other calendars), then run again.'
);
}
var tz;
try {
tz = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
} catch (e) {
tz = Session.getScriptTimeZone();
}
try {
if (!tz) tz = cal.getTimeZone();
} catch (e2) {}
if (!tz) tz = 'UTC';
var start = new Date(y, 0, 1);
var end = new Date(y + 1, 0, 1);
var events = cal.getEvents(start, end);
var seen = {};
var out = [];
function pad_(n) { return (n < 10 ? '0' : '') + n; }
function addDaysUtc_(ymd, n) {
var p = ymd.split('-');
var cur = new Date(Date.UTC(Number(p[0]), Number(p[1]) - 1, Number(p[2]) + n));
return cur.getUTCFullYear() + '-' + pad_(cur.getUTCMonth() + 1) + '-' + pad_(cur.getUTCDate());
}
function civilYmd_(date, zone) {
return Utilities.formatDate(date, zone, 'yyyy-MM-dd');
}
function addYmd_(ymd) {
if (ymd.substring(0, 4) !== String(y)) return;
if (seen[ymd]) return;
seen[ymd] = true;
out.push(ymd);
}
for (var i = 0; i < events.length; i++) {
var ev = events[i];
var startYmd;
var endYmd;
var allDay = false;
try { allDay = ev.isAllDayEvent(); } catch (e3) { allDay = false; }
if (allDay) {
startYmd = civilYmd_(ev.getAllDayStartDate(), tz);
endYmd = civilYmd_(ev.getAllDayEndDate(), tz);
if (endYmd <= startYmd) {
addYmd_(startYmd);
continue;
}
for (var d = startYmd; d < endYmd; d = addDaysUtc_(d, 1)) addYmd_(d);
} else {
startYmd = civilYmd_(ev.getStartTime(), tz);
endYmd = civilYmd_(ev.getEndTime(), tz);
addYmd_(startYmd);
// Timed events that cross midnight: include each civil day up to, not past, the end instant's date if end is exactly midnight.
if (endYmd > startYmd) {
var t = addDaysUtc_(startYmd, 1);
var last = endYmd;
// If the event ends at midnight, the end date is exclusive.
var endTime = ev.getEndTime();
var endIsMidnight = Utilities.formatDate(endTime, tz, 'HH:mm:ss') === '00:00:00';
if (endIsMidnight) last = endYmd;
else last = addDaysUtc_(endYmd, 1);
for (; t < last; t = addDaysUtc_(t, 1)) addYmd_(t);
}
}
}
out.sort();
return out;
}
Example
function refreshPublicHolidays() {
var year = Number(Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy'));
var publicDays = listHolidayDates(year);
var sheet = SpreadsheetApp.getActive().getSheetByName('Holidays') ||
SpreadsheetApp.getActive().insertSheet('Holidays');
var existing = sheet.getLastRow() > 1
? sheet.getRange(2, 1, sheet.getLastRow() - 1, 2).getDisplayValues()
: [];
var office = existing.filter(function (r) { return r[1] === 'Office'; });
var seen = {};
office.forEach(function (r) { seen[r[0]] = true; });
var rows = office.slice();
publicDays.forEach(function (d) {
if (seen[d]) return;
seen[d] = true;
rows.push([d, 'Public']);
});
rows.sort(function (a, b) { return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0; });
sheet.clearContents();
sheet.getRange(1, 1, 1, 2).setValues([['Date', 'Source']]);
if (rows.length) sheet.getRange(2, 1, rows.length, 2).setValues(rows);
}
Notes
- Other countries use a different id (for example
en.uk#holiday@group.v.calendar.google.com). Pass{calendarId}for those, or for a calendar you already own. - A two-day all-day event is two dates. Events that fall outside the year are dropped.
- This reads the calendar; it does not create or change events.
Happy Coding!
