Google Docs – Using Current Date as a Variable

google docsgoogle-apps-script

Is it possible to add (insert) a variable for the current date into a Google Docs that would automatically update each time I open the document?

Some criteria:

  • The date position should be variable, i.e. allowing me to insert the date a different positions of a page/paragraph

  • The document should still be shareable, i.e. people opening my document will also be displayed with the current date

Best Answer

Short answer

At this time, variables is not a built-in feature of Google Docs and Google Apps Script, the platform to extend Google Docs, does not include a class or method to handle them.

Alternatives

Alternative 1

One alternative is use a text pattern but you should be sure that it will match only the date that you want to update.

Alternative 2

Another alternative is to use the class NamedRange but bear in mind that

  1. moving the range will make that it lose its name1.
  2. replacing text in a named range with multiple elements only works the first time2.

Code:

The following code, intended to be used in a script bound to a Google Document, has two main functions:

  1. Insert today's date
  2. Update today's date

For debugging purposes are being used

  1. date and time, instead of date only.
  2. custom menus to trigger the main functions.

"Known-issues": The update function replaces the whole paragraph.

To test the code, copy it, then go to your Google Docs, create a new document, click on Tools > Script Editor, select Blank Project, paste the code, save the project, assign a name, run on time to authorize the app, close your doc and open again. A new menu called "Utilities" will be displayed. From there you can call the main functions.

function onOpen() {
  // Add a menu with some items, some separators, and a sub-menu.
  DocumentApp.getUi().createMenu('Utilities')
      .addItem('Insert Today\'s Date', 'insertTodayAtCursor')
      .addItem('Update Today\'s Date', 'setTodayNamedRange')
      .addToUi();
}

function todayDate(){
  return Utilities.formatDate(new Date(), "GMT-5", "yyyy-MM-dd'T'HH:mm:ss'Z'"); // "yyyy-MM-dd"
}

/**
 * Inserts the today's date at the current cursor location and create a NamedRange.
 */
function insertTodayAtCursor() {
  var str = 'testToday';
  var doc = DocumentApp.getActiveDocument();
  var cursor = doc.getCursor();

  if (cursor) {
    // Attempt to insert today's date at the cursor position. If insertion returns null,
    // then the cursor's containing element doesn't allow text insertions.
    var date = todayDate();
    var element = cursor.insertText(date);
    if (element) {
      var rangeBuilder = doc.newRange();
      rangeBuilder.addElement(element);
      return doc.addNamedRange(str, rangeBuilder.build()); 
    } else {
      DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
    }
  } else {
    DocumentApp.getUi().alert('Cannot find a cursor in the document.');
  }
}

function setTodayNamedRange(){
  var str = 'testToday';
  var doc = DocumentApp.getActiveDocument();
  // Retrieve the named range
  var namedRanges = doc.getNamedRanges();
  var newRange = doc.newRange();
  var date = todayDate();
  for(var i=0; i<namedRanges.length; i++){

    if(namedRanges[i].getName() == str){

      var rangeElement = namedRanges[i].getRange().getRangeElements();

      for (var j=0; j<rangeElement.length; j++){

        var element = rangeElement[j].getElement().asText().editAsText().setText(date);
        newRange.addElement(element);
      }
    }
  }
  doc.addNamedRange(str, newRange.build());
}


Below there are some items of different kind (questions, specifications, etc.) that could serve to get inspiration or point to the "right direction" to find a "solution"


Footnotes