Week Start Key

weekStartKey(date, tz) returns the Monday of that date's week as yyyy-MM-dd, computed in the given timezone. Use it as a stable grouping key for weekly reports so Sunday night and Monday morning do not fall into different weeks depending on who runs the script.

When to use

  • Grouping rows into a weekly summary tab
  • Naming a file or a log tab for "the week of …"
  • Any job that should agree with a sheet timezone, not the server's

How to use this snippet

/** * Monday of the week containing date, as yyyy-MM-dd in tz. * Weeks start on Monday. Sunday belongs to the week that started the previous Monday. * tz defaults to Session.getScriptTimeZone() if omitted. * * @param {Date|string|number} date * @param {string} [tz] e.g. "America/New_York" * @return {string} */ function weekStartKey(date, tz) { tz = tz || Session.getScriptTimeZone(); var d = date instanceof Date ? date : new Date(date); if (isNaN(d.getTime())) throw new Error('weekStartKey: invalid date'); var ymd = Utilities.formatDate(d, tz, 'yyyy-MM-dd'); var p = ymd.split('-'); var utc = new Date(Date.UTC(+p[0], +p[1] - 1, +p[2], 12, 0, 0)); var dow = utc.getUTCDay(); // 0=Sun var delta = dow === 0 ? 6 : dow - 1; utc.setUTCDate(utc.getUTCDate() - delta); var y = utc.getUTCFullYear(); var m = utc.getUTCMonth() + 1; var day = utc.getUTCDate(); return y + '-' + (m < 10 ? '0' : '') + m + '-' + (day < 10 ? '0' : '') + day; }

Example

function weekOfRow(date) { var tz = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); return weekStartKey(date, tz); // e.g. 2027-03-22 }

Notes

  • The calendar date is taken in tz first, then stepped back to Monday, so a late Sunday in New York is not treated as Monday UTC.
  • Invalid dates throw. Pass a real Date (Sheets serials already arrive as Date from getValues()).
  • This is not an ISO week-number (2027-W13). It is the Monday date, which sorts and groups cleanly as a string.
  • For other timezone-safe formatting, see Format In Spreadsheet Timezone.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free snippets — plus optional Co-Pilot when you want a boost (Day Pass — $3, or 1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension