Skip to content

Instantly share code, notes, and snippets.

@ekohilas
Last active Jul 17, 2020
Embed
What would you like to do?
Inserts an RFC2822 Timestamp at the cursor location of a Google Document
// https://developers.google.com/apps-script/reference/document
function insertTimeStampAtCursor() {
const doc = DocumentApp.getActiveDocument();
const selection = doc.getSelection();
const cursor = doc.getCursor();
const dateTimeString = rfc2822Datetime();
if (selection) {
const selectedElements = selection.getRangeElements();
// might break if it's not text
selectedElements[0]
.getElement()
.asText()
.setText(dateTimeString)
.setFontFamily("Roboto Mono");
for (var i = 1; i < selectedElements.length; i++) {
const selectedElement = selectedElements[i];
const element = selectedElement.getElement();
if (selectedElement.isPartial()) {
element
.asText()
.deleteText(
selectedElement.getStartOffset(),
selectedElement.getEndOffsetInclusive()
);
} else {
element.removeFromParent();
}
}
} else if (cursor) {
const element = cursor.insertText(dateTimeString);
if (element) {
element.setFontFamily("Roboto Mono");
} else {
DocumentApp.getUi().alert("Cannot insert text at this cursor location.");
}
} else {
DocumentApp.getUi().alert("Cannot find a cursor or selection in the document.");
}
}
function rfc2822Datetime() {
const now = new Date();
const timeZone = Session.getScriptTimeZone();
const rfc2822Format = "EEE, dd MMM yyyy HH:mm:ss Z";
const dateTimeString = Utilities.formatDate(now, timeZone, rfc2822Format);
return dateTimeString;
}
function menu() {
DocumentApp.getUi().createMenu("Utils")
.addItem("Insert timestamp", "insertTimeStampAtCursor")
.addToUi();
}
function onOpen() {
menu();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment