Skip to content

Instantly share code, notes, and snippets.

@russianryebread
Forked from thomxc/InsertDate.gs
Last active August 29, 2015 14:22
Show Gist options
  • Save russianryebread/19569c7d723122eab9a1 to your computer and use it in GitHub Desktop.
Save russianryebread/19569c7d723122eab9a1 to your computer and use it in GitHub Desktop.
Inserts a date at the cursor location in Google Docs
/**
* @OnlyCurrentDoc Limits the script to only accessing the current document.
*/
var now_date = new Date();
// Menu Titles
var title = [
Utilities.formatDate(now_date, "GMT", "MM/dd/yyyy"),
Utilities.formatDate(now_date, "GMT", "yyyy-MM-dd"),
Utilities.formatDate(now_date, "GMT", "EEE, MMMM d, yyyy"),
Utilities.formatDate(now_date, "GMT", "MMM d, yy")
];
/**
* Runs when the add-on is installed; calls onOpen() to ensure menu creation and
* any other initializion work is done immediately.
*
* @param {Object} e The event parameter for a simple onInstall trigger.
*/
function onInstall(e) {
onOpen(e);
}
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('Utilities')
.addSubMenu(ui.createMenu('Insert Date...')
.addItem(title[0], 'menuItem1')
.addItem(title[1], 'menuItem2')
.addItem(title[2], 'menuItem3')
.addItem(title[3], 'menuItem4'))
.addToUi();
}
function menuItem1() {
insertAtCursor(title[0]);
}
function menuItem2() {
insertAtCursor(title[1]);
}
function menuItem3() {
insertAtCursor(title[2]);
}
function menuItem4() {
insertAtCursor(title[3]);
}
/**
* Inserts the date at the current cursor location in boldface.
*/
function insertAtCursor(date) {
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
var element = cursor.insertText(date);
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