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.
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, for example to see how many days a task is overdue.
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
Sets the time on a date to midnight, then adds a day. Use the two dates to check whether another date falls today.
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, 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/**
* @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, for example to clean 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
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.
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 arrays of a fixed size, so you can process or email 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. Write one into a row so a later run can recognize that row.
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, for example to space 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
Remove duplicate people from a contact list. The script keeps the first row for each email address and writes those rows to a tab named Clean, leaving the original list as it is.
- Task guide Email yourself a weekly sheet summary
Get a short email every Friday with the numbers from an Orders tab: how many rows it has, the total of column C, and how many rows are not Done. Run the setup function once to install the weekly trigger.
- Task guide Back up a spreadsheet to Drive every week
Keep a dated copy of a spreadsheet in a Drive folder. Run the setup function once, and every Monday morning the script saves a new copy with the date in its name.
- 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() returns that rectangle as an array of rows, and each row is an array of cell values.