Insert date time in google document

rbregt picture rbregt · Nov 27, 2012 · Viewed 96.6k times · Source

I would like to insert a timestamp (date and/or time) into Google Documents. The support documentation () says that there should be a keyboard shortcut, but it does not work in my environment (Win7 + IE9).

Can anyone provide me with a Google Apps script to achieve this?

Answer

Ryan Heitner picture Ryan Heitner · Feb 10, 2014

This works well

In Google Docs : Tools -> Open Script Editor and save this script

function onOpen() {
  var ui = DocumentApp.getUi();
  // Or FormApp or SpreadsheetApp.
  ui.createMenu('Custom Menu')
      .addItem('Insert Date', 'insertDate')
      .addToUi();

}

function insertDate() {
  var cursor = DocumentApp.getActiveDocument().getCursor();
  if (cursor) {
      // Attempt to insert text at the cursor position. If insertion returns null,
      // then the cursor's containing element doesn't allow text insertions.
      var d = new Date();
      var dd = d.getDate();
      dd = pad(dd, 2)
      var mm = d.getMonth() + 1; //Months are zero based
      mm = pad(mm, 2)
      var yyyy = d.getFullYear();
      var date = dd + "-" + mm + "-" + yyyy;
      var element = cursor.insertText(date);
      if (element) {
        element.setBold(true);
      } else {
        DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
      }
    } else {
      DocumentApp.getUi().alert('Cannot find a cursor in the document.');
  }

}
function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

Reload the Doc, Accept the permissions.