11

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

  • Which time zone should be used to calculate the current date? – Rubén Aug 5 '15 at 14:17
  • To have it versatile, maybe defined by the user himself in the settings? Or can it be somehow fetched from the user's Google Docs settings automatically? – orschiro Aug 6 '15 at 6:52
  • 1
    Just added my coding attempt. Regarding the time zone, I used GMT-5 but it could be easily changed to the one that you needs. It's not a complete solution. – Rubén Aug 6 '15 at 18:22
9

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

  • Does that mean it is not possible? – Jacob Jan Tuinstra Apr 24 '15 at 23:12
  • @JacobJanTuinstra: IMHO, yes, it isn't possible. What could be possible is to find a workaround but it's necessary more context. I think that asking for that information should be done in comments, but I can't comment anywhere yet :) – Rubén Apr 24 '15 at 23:28
  • 1
    @orschiro I'm glad to know that it worked for you. Rather than refactored into a Chrome extension, could be into a Google Docs add-on, I think. – Rubén Aug 7 '15 at 12:40
  • 1
    @ChristopherFrancisco: The code is intended to be used on bounded script but it could be adapted to be used from your app but that is a different question that it's very likely be more appropriate for Stack Overflow. – Rubén Jan 4 '17 at 18:56
  • 1
    @ChristopherFrancisco I just added a link to the official guide about scripts bounds to Google Docs editor files. – Rubén Jan 4 '17 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.