nabinkm

InsertDateTime Google

Jan 9th, 2015
448
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function onOpen() {
  2.   var ui = DocumentApp.getUi();
  3.   // Or FormApp or SpreadsheetApp.
  4.   ui.createMenu('Insert Date')
  5.       .addItem('Insert Date', 'insertDate')
  6.       .addToUi();
  7.  
  8. }
  9.  
  10. function insertDate() {
  11.   var cursor = DocumentApp.getActiveDocument().getCursor();
  12.   if (cursor) {
  13.       // Attempt to insert text at the cursor position. If insertion returns null,
  14.       // then the cursor's containing element doesn't allow text insertions.
  15.       var d = new Date();
  16.       var dd = d.getDate();
  17.       var hrs = d.getHours();
  18.       var min = d.getMinutes();
  19.       dd = pad(dd, 2)
  20.       var mm = d.getMonth() + 1; //Months are zero based
  21.       mm = pad(mm, 2)
  22.       var yyyy = d.getFullYear();
  23.     var date =  "Date: "+mm + "-" +dd + "-" + yyyy+ "::"+hrs+":"+min +"\n";
  24.       var element = cursor.insertText(date);
  25.       if (element) {
  26.         element.setBold(true);
  27.       } else {
  28.         DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
  29.       }
  30.     } else {
  31.       DocumentApp.getUi().alert('Cannot find a cursor in the document.');
  32.   }
  33.  
  34. }
  35. function pad (str, max) {
  36.   str = str.toString();
  37.   return str.length < max ? pad("0" + str, max) : str;
  38. }
  39.  
  40.  
  41. /*Note:
  42. If you add the following function call inside the onOpen() function:
  43.   insertDate();
  44. Then you will get automated insertion of date and time. Great for logging the daily notes!!!
  45. */
Add Comment
Please, Sign In to add comment