Snippets · 12 functions
Dates, text, and array snippets
Each one is a complete, runnable function you can paste into the Apps Script editor to see a date, currency, or array helper work on real values.
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 using the script's own time zone, so the result matches what the reader expects to see.
UtilitiesSessionfunction 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.
Utilitiesfunction 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, useful for measuring how overdue something is.
Utilitiesfunction 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
Zeroes out the time on a date to get midnight, then adds a day, a pattern used for "is this today" checks.
Utilitiesfunction 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 safely
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/**
* @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.
Utilitiesfunction 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, useful for cleaning up names typed in lowercase.
Utilitiesfunction 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.
Utilitiesfunction 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
Walks a list of rows and collects them into an object keyed by one column, a common step before summarizing data.
Utilitiesfunction 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 fixed-size arrays, useful for processing or emailing a list in batches.
Utilitiesfunction 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, useful for tagging a row so a later run can recognize it.
Utilitiesfunction 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, useful for spacing out calls to another service.
Utilitiesfunction 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
- Task guide Copy unique rows to a clean tab
The script reads your list, keeps the first row for each email address, and rewrites a tab named Clean. The source tab is never changed.
- Task guide Email yourself a weekly sheet summary
Run the setup function once. Each Friday the script reads the Orders tab, counts the nonblank rows, totals column C, counts the rows that are not Done, and emails the account that installed it.
- Task guide Back up a spreadsheet to Drive every week
Run the setup function once. Every Monday morning the script copies the spreadsheet into a Drive folder and puts the date in the copy name. The original is never touched.
- Basics Dates, time zones, and Utilities.formatDate
A Date holds one instant in time. Use Utilities.formatDate(date, timeZone, pattern) and Session.getScriptTimeZone() to format it in the right time zone.
- Basics Rows, columns, and 2D arrays in Sheets scripts
A range is a rectangle of cells. getValues() hands you that rectangle as an array of rows, and each row is an array of cell values.