I would like to insert a timestamp (date and/or time) into Google Documents. The support documentation () says that there should be a keyboard shortcut, but it does not work in my environment (Win7 + IE9).
Can anyone provide me with a Google Apps script to achieve this?
Best Answer
This works well
In Google Docs : Tools -> Open Script Editor and save this script
function onOpen() {var ui = DocumentApp.getUi();// Or FormApp or SpreadsheetApp.ui.createMenu('Custom Menu').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();dd = pad(dd, 2)var mm = d.getMonth() + 1; //Months are zero basedmm = pad(mm, 2)var yyyy = d.getFullYear();var date = dd + "-" + mm + "-" + yyyy;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;}
Reload the Doc, Accept the permissions.
I am not sure if an add-on falls under the category Google Apps Script you were asking for, bug Text Factory provides the feature to insert a time-stamp.
Here is an edited version (of the one already provided) that prints out a date stamp including the time.
Here is an example of the output: 2:43:21 AM EST 26-03-2014
function onOpen() {var ui = DocumentApp.getUi();// Or FormApp or SpreadsheetApp.ui.createMenu('Insert Date').addItem('Insert Date', 'insertDate').addToUi();}function insertTime() {var d = new Date();var timeStamp = d.getTime(); // Number of ms since Jan 1, 1970// OR:var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance}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();dd = pad(dd, 2)var mm = d.getMonth() + 1; //Months are zero basedmm = pad(mm, 2)var yyyy = d.getFullYear();var timeStamp = d.getTime(); // Number of ms since Jan 1, 1970var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instancevar date = currentTime + " " + dd + "-" + mm + "-" + yyyy;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;}
If you want to get automatically current date after open document, you can add this script:
In Google Docs: Tools -> Open Script Editor and save this script:
/** * After open document actualize part with text "Generated" to "Generated [actual date]".*/function onOpen() { var body = DocumentApp.getActiveDocument().getBody();var date = Utilities.formatDate(new Date(), "GMT", "dd.MM.yyyy");// Clear the text surrounding "Apps Script", with or without text.body.replaceText("^Generated.*$", "Generated " + date); }
In the document body you must have text "Generated".
Create a new Sheets document
In A1, put Date:
and B1, put the formula NOW()
. I named the sheet current-date
, but you can name it whatever you want. This document will simply sit on your drive to server as a "date keeper" for all of your Docs documents.
Format Cell as Date
Select cell B1 and choose Number >> Date
from the Format
menu.
Select Cells and Copy
Select cells A1 and B1, right click, and choose Copy
Paste and Link to Docs Document
Right click in your Docs document where you want to paste the cells and click Paste
. Docs should ask you if you want to link these cells to the source document. Select Link to spreadsheet
and then click Paste
.
Get Rid of the Borders
To get rid of the borders, right click on the inserted cells and select Table Properties
.
Now set Table Border
to 0pt
and click OK
.
Final Result
You should end up with something like this. You can drag the edges of the cells to make them bigger or smaller and change the font and text size of the cells as well. If you make the text bigger, the text will wrap inside the cells so you will need to make them wider.
Updating the Date
Now whenever you open your document with the linked cells and the date has changed, you should see this. Click Update
and your date will be updated to today's date. There is no need to ever open the current-date
spreadsheet!
Enjoy!
For Docs, you are probably out of luck, as there appears to be no hotkey for that, and support for scripting from within Docs is lacking (Spreadsheets would be a different story). Since you're on Windows, you can avail yourself of autohotkey, though. This video, while way too long, shows assigning a global hotkey combo to insert the current date anywhere. With that, you can insert your date/time anywhere you want to while using your Windows system. (You can customize it to be only active in certain applications, such as IE, if you want to get wacky with it)
Because extra key-strokes are being used to insert the date from the menu, my solution is a batch file, sts.cmd, that stores the date-time into the clip-board when called, enabling an easy Windows+R, sts, Ctrl+V to get and paste. If you are adding extra keystrokes to get the date into the doc anyway you might as well just paste it in.The code is
@ECHO OFFfor /f "tokens=1-12 delims=/:. " %%d in ("%time%") do SET MYTIME= %%d:%%e:%%ffor /f "tokens=1-12 delims=/:. " %%d in ("%date%") do SET MYDATE= %%g-%%e-%%fSET MYTS=%MYDATE%%MYTIME%ECHO | SET /p dummyname=%MYTS%|clip
This works for me until GDocs comes up with an embeddable function that will update the display date to the current date each time the doc is opened.
On MacOS, I used Automator.
I created a Service that works with Chrome, takes no input, and runs a shell script and sends the output to the clipboard. The shell script is very basic:
DateTime=`date "+%Y-%m-%d %H:%M"`echo $DateTime
I could have done without the intermediate variable and just run the date command, but I had the idea that I might want to do extra processing and formatting. Note that if you want to include spaces in your formatting of the date string, the formatting argument must be in quotes. The screen shot uses an underbar instead.
With the script saved, I went to System Settings > Keyboard > Shortcuts, I found my script DateTime2CB.workflow in the Text section and gave it a hotkey. There's no easy way of finding out what hotkeys are in use.
I could have made it for any app (and if I find myself trying to use it other apps I still might do that), but for now it's Chrome only. I could also have had the shell script pipe the output of date to the clipboard, pbcopy on Mac, as above (using "clip"). I've tested both methods and they work.
I added the same script to another Mac and it was set up to insist that the Automator file (name.workflow) be saved in iCloud. in that context, it was not listed in the Keyboard settings. To fix that, I had to reopen the saved iCloud file in Automator using Open > Recent. It asked if I wanted to install the file in Services. A yes answer at that point saved it on my local system and I could find it under Settings > Keyboard > Shorcuts > Services.
I hope this helps other Mac users.
August
Try this:
function insertTimestamp() {var ss = SpreadsheetApp.getActiveSpreadsheet();var cell = ss.getActiveCell();cell.setValue(new Date());// sets the cells format to month/day/year.// Remove if you want time inserted as wellcell.setNumberFormat("MM/dd/yyyy") }
This works on spreadsheets not sure if you were looking for other docs.
Create a Spreadsheet Today in google docs. Put the date in B1 as Today() Format it in C1 using the function Text(B1,"dddd, mmmm d, yyyy")Then use the following script (you will need the url of the Today Spreadsheet
function myFunction() {var doc = DocumentApp.getActiveDocument();var body1 = doc.getBody();var style1 = {};style1[DocumentApp.Attribute.BOLD] = true;var text1 = doc.editAsText();body1.appendHorizontalRule(); var wb = SpreadsheetApp.openByUrl('spreadsheet url');var ss = wb.getSheetByName('Today');var r = ss.getRange('C1');var date1 = r.getValues();var par1 =body1.appendParagraph(date1[0]);par1.setAttributes(style1);}