Google-apps-script – Shortcut to insert current date in Google Docs

google docsgoogle-apps-script

For example, in MS Word I can insert the current date by typing current year and dash

2018- // ... and current date appears automatically, like 2018-05-20 Sun

Is there something similar in Google Docs?

Best Answer

It’s possible to insert todays date through a macro.

Open your Google Document and under Tools select Script editor. This opens Google's script editor where it’s possible to create macros for Google Documents.

Paste this script and save it as Date Macro or something: (also available here)

/**
 * The onOpen function runs automatically when the Google Docs document is
 * opened. Use it to add custom menus to Google Docs that allow the user to run
 * custom scripts. For more information, please consult the following two
 * resources.
 *
 * Extending Google Docs developer guide:
 *     https://developers.google.com/apps-script/guides/docs
 *
 * Document service reference documentation:
 *     https://developers.google.com/apps-script/reference/document/
 */
function onOpen() {
  // Add a menu with some items, some separators, and a sub-menu.
  DocumentApp.getUi().createMenu('Utilities')
      .addItem('Insert Date', 'insertAtCursor')
      .addToUi();
}

/**
 * Inserts the date at the current cursor location in boldface.
 */
function insertAtCursor() {
  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 date = Utilities.formatDate(new Date(), "IST", "yyyy MMM dd"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
    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.');
  }
}

Now refresh or reopen your document and a new menu item appears: Utilities. Under this menu an item appears called Insert Date. Click that to insert todays date at your cursor position.

To change the format of the date you need to change the “format” used in the script. The format can contain the following characters: yyyy-MM-dd'T'HH:mm:ss'Z'

To clarify, this script merely inserts today's date at the cursor location for the day you execute the utility. That's not precisely the same as the =today() function in Google Sheets, which updates the date to the current date whenever you open the spreadsheet. However, this script will save you the trouble of looking up the date and typing it on the day that you execute the script.

Source: https://webapps.stackexchange.com/a/58981/216802

Can someone mark this question as duplicate, I don't have enough reputaion points as of now.