Wednesday, June 1, 2016

Insert the date and time into the google docs

This first appeared here ... http://ajabgajab.blogspot.com/2015/01/insert-date-and-time-into-google-docs.html 
This is how you insert the date and time to the google docs

1. Go to the Google document/new document.
2. Go to the Tools/Script Editor, and insert the following script at the bottom of the scripts.
This will create a new menu. You can modify the code to change the appearance of the month/date.
3. See the end note to add automated date entry!

The code is available below/ at pastebin.
http://pastebin.com/QFpTRQ3h




function onOpen() {
  var ui = DocumentApp.getUi();
  // Or FormApp or SpreadsheetApp.
  ui.createMenu('Insert Date')
      .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();
      var hrs = d.getHours();
      var min = d.getMinutes();
      dd = pad(dd, 2)
      var mm = d.getMonth() + 1; //Months are zero based
      mm = pad(mm, 2)
      var yyyy = d.getFullYear();
    var date =  "Date: "+mm + "-" +dd + "-" + yyyy+ "::"+hrs+":"+min +"\n";
      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;
}

--- 
--> 

Note:
If you add the following function call inside the onOpen() function:
  insertDate();
Then you will get automated insertion of date and time. Great for logging the daily notes!!!




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

  insertDate();

}

No comments: