Skip to content

Snippets · 12 functions

Dates, text, and array snippets

Short functions for dates, currency, text, and arrays. Run one in the Apps Script editor to see its result in the Execution log.

How to use these

Set up before you run

Copy a snippet into a script file, read its setup and notes, change the placeholder values, and save. For functions meant to run manually, choose the function name in the toolbar and press Run. Results appear in the Execution log unless the description says otherwise.

1

Format today's date

Formats the current date in the time zone set under Project Settings, which Session.getScriptTimeZone() returns.

UtilitiesSession
Code.gs
function logTodaysFormattedDate() {
  const timeZone = Session.getScriptTimeZone();
  const formatted = Utilities.formatDate(new Date(), timeZone, 'yyyy-MM-dd');
  Logger.log('Today is ' + formatted);
}

2

Add days to a date

Creates a new date a set number of days after a starting date, without changing the original date.

Utilities
Code.gs
function addDaysToDate() {
  const startDate = new Date();
  const daysToAdd = 10;
  const laterDate = new Date(startDate.getTime());
  laterDate.setDate(laterDate.getDate() + daysToAdd);
  Logger.log('10 days from now: ' + laterDate);
}

3

Days between two dates

Counts the whole number of days between two dates, for example to see how many days a task is overdue.

Utilities
Code.gs
function logDaysBetweenDates() {
  const startDate = new Date(2026, 0, 1);
  const endDate = new Date(2026, 2, 15);
  const millisecondsPerDay = 24 * 60 * 60 * 1000;
  const daysBetween = Math.round((endDate.getTime() - startDate.getTime()) / millisecondsPerDay);
  Logger.log('Days between: ' + daysBetween);
}

4

Start of today and start of tomorrow

Sets the time on a date to midnight, then adds a day. Use the two dates to check whether another date falls today.

Utilities
Code.gs
function logStartOfTodayAndTomorrow() {
  const startOfToday = new Date();
  startOfToday.setHours(0, 0, 0, 0);
  const startOfTomorrow = new Date(startOfToday.getTime());
  startOfTomorrow.setDate(startOfTomorrow.getDate() + 1);
  Logger.log('Start of today: ' + startOfToday);
  Logger.log('Start of tomorrow: ' + startOfTomorrow);
}

5

Turn a cell value into a Date, or null

Accepts either a real Date object or valid yyyy-MM-dd text, the two forms a Sheet cell can hand back, and returns a Date or null.

UtilitiesSession
Code.gs
/**
 * @param {unknown} value
 * @return {Date|null}
 */
function toSafeDate(value) {
  if (value instanceof Date && !isNaN(value.getTime())) return value;
  if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
    const [year, month, day] = value.split('-').map(Number);
    // setFullYear avoids Date's 1900 offset for years 0 through 99.
    const date = new Date(0);
    date.setHours(0, 0, 0, 0);
    date.setFullYear(year, month - 1, day);
    if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) return null;
    return date;
  }
  return null;
}

function logSafeDateResult() {
  const result = toSafeDate('2026-09-15');
  Logger.log(result ? Utilities.formatDate(result, Session.getScriptTimeZone(), 'yyyy-MM-dd') : 'Not a date');
}

Good to know. A Sheet cell formatted as a date arrives as a Date object already. Only text cells need the yyyy-MM-dd parsing branch.

6

Format a number as currency

Rounds a number to two decimal places and adds thousands separators, without relying on locale-specific formatting.

Utilities
Code.gs
function formatAsCurrency() {
  const amount = 1234567.5;
  const rounded = amount.toFixed(2);
  const parts = rounded.split('.');
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  const formatted = '$' + parts.join('.');
  Logger.log(formatted);
}

7

Capitalize the first letter of each word

Splits text on spaces and capitalizes the first letter of every word, for example to clean up names typed in lowercase.

Utilities
Code.gs
function capitalizeEachWord() {
  const text = 'quarterly budget review notes';
  const capitalized = text
    .split(' ')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
  Logger.log(capitalized);
}

8

Remove duplicates from a list

Uses a Set to keep only the first copy of each value in a list, then converts it back to an array.

Utilities
Code.gs
function removeDuplicateValues() {
  const values = ['Apple', 'Banana', 'Apple', 'Cherry', 'Banana'];
  const uniqueValues = Array.from(new Set(values));
  Logger.log(uniqueValues.join(', '));
}

9

Group rows by a column value into an object

Loops over a list of rows and groups them into an object keyed by the value in one column, a common step before summarizing data.

Utilities
Code.gs
function groupRowsByStatus() {
  const rows = [
    ['Ana', 'Open'],
    ['Ben', 'Closed'],
    ['Cara', 'Open']
  ];
  /** @type {Record<string, string[]>} */
  const grouped = {};
  rows.forEach((row) => {
    const [name, status] = row;
    if (!grouped[status]) grouped[status] = [];
    grouped[status].push(name);
  });
  Logger.log(JSON.stringify(grouped));
}

10

Split a long list into chunks

Breaks a long array into smaller arrays of a fixed size, so you can process or email a list in batches.

Utilities
Code.gs
function splitListIntoChunks() {
  const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  const chunkSize = 3;
  /** @type {string[][]} */
  const chunks = [];
  for (let i = 0; i < items.length; i += chunkSize) {
    chunks.push(items.slice(i, i + chunkSize));
  }
  Logger.log(JSON.stringify(chunks));
}

11

Generate a unique ID

Uses Utilities.getUuid to create a random unique identifier. Write one into a row so a later run can recognize that row.

Utilities
Code.gs
function generateUniqueId() {
  const uniqueId = Utilities.getUuid();
  Logger.log('Generated ID: ' + uniqueId);
}

12

Pause briefly with Utilities.sleep

Waits for a set number of milliseconds before continuing, for example to space out calls to another service.

Utilities
Code.gs
function pauseBetweenApiCalls() {
  Logger.log('Starting first call.');
  Utilities.sleep(2000);
  Logger.log('Resuming after a 2 second pause.');
}

Good to know. Utilities.sleep pauses the whole script, and the wait counts against the runtime limit, so avoid calling it inside a loop that runs many times.

Keep going

See these in a complete task

All snippet collections