09:15:01 # Life Adding a new date entry using GAS on Google Docs. When I am writing a diary, or having a weekly meeting, it is sometimes tedious to add today's date every time. I can automate such tasks with GAS. There's a onOpen method that gets called every time a doc is opened, and you can use that to implement adding the latest date when the latest date does not match.
/** * @OnlyCurrentDoc */ function onOpen(e) { DocumentApp.getUi().createAddonMenu() .addItem('Add today', 'addToday') .addToUi(); addToday(); } /** * Add today's date string to top of the document. */ function addToday() { if (!LockService.getDocumentLock().tryLock(10000)) { Logger.log("Could not get lock"); return; } var body = DocumentApp.getActiveDocument().getBody(); var paragraphs = body.getParagraphs(); var firstParagraph = paragraphs[0].getText(); var d = new Date(); var todayDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate(); Logger.log('today is %s and your doc says %s', todayDate, firstParagraph); if (todayDate != firstParagraph) { body.insertListItem(0, "").setGlyphType(DocumentApp.GlyphType.BULLET); body.insertParagraph(0, todayDate).setHeading(DocumentApp.ParagraphHeading.HEADING1); Logger.log('inserted today!'); } }