Created
February 23, 2017 01:18
-
-
Save omurphy27/f9540f3524c7e223a36eb015f6e307b8 to your computer and use it in GitHub Desktop.
Google Docs Script for Inserting Formatted Date with Month Name via a Macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Helper functions to make formatting the date easier | |
*/ | |
Date.prototype.getMonthNameShort = function() { | |
return Date.month_names_short[ this.getMonth() ]; | |
}; | |
Date.month_names_short = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; | |
Date.prototype.getDateEnding = function() { | |
var currentDate = this.getDate(); | |
if ( [1,21,31].indexOf( currentDate ) > -1 ) { | |
return Date.date_endings[0]; | |
} else if ( [2,22].indexOf( currentDate ) > -1 ) { | |
return Date.date_endings[1]; | |
} else if ( [3,23].indexOf( currentDate ) > -1 ) { | |
return Date.date_endings[2]; | |
} else { | |
return Date.date_endings[3]; | |
} | |
}; | |
Date.date_endings = [ 'st','nd','rd','th' ]; | |
/** | |
* 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 sentence current formatted 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 ndate = new Date(); | |
var fdate = ndate.getMonthNameShort() + ndate.getDate() + ndate.getDateEnding() + '-' + ndate.getFullYear(); | |
var element = cursor.insertText(fdate); | |
if ( !element ) { | |
DocumentApp.getUi().alert('Cannot insert text at this cursor location.'); | |
} | |
} else { | |
DocumentApp.getUi().alert('Cannot find a cursor in the document.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment