Is there a way in Google Docs to automatically update the date in a header of the page, so that whenever I print the document it will have today's date?
2 Answers
This can only be done with a script, to be entered in Tools > Script Editor. Once you save the script, it will run automatically every time the document is open, updating the date in the header. Here is one way to do this:
function onOpen() {
var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
var pattern = "\\b\\d{4}-\\d{2}-\\d{2}\\b";
var header = DocumentApp.getActiveDocument().getHeader();
header.editAsText().replaceText(pattern, date);
}
This assumes that you want the date format 2016-04-26 and have already created document header with a date in this format (the header may contain other text besides the date, such as "Date: "). The script works by replacing the date with today's date.
You may also want to adjust the timezone.
Other formats
- 04/26/2016: use
"MM/dd/yyyy"
on the second line and"\\b\\d{2}/\\d{2}/\\d{4}\\b"
on the third - 26.04.2016: use
"dd.MM.yyyy"
on the second line and"\\b\\d{2}\\.\\d{2}\\.\\d{4}\\b"
on the third.
-
Thanks. This looks to be exactly what I needed. However, I get an error when I run it. Could you please help! TypeError: Cannot call method "editAsText" of null. (line 5, file "Code") Jan 29, 2017 at 17:31
I tweaked my script allowing for single digit month and day by substituting {2} for {1,2} and changing the date format:
function onOpen() {
var date = Utilities.formatDate(new Date(), "EST", "M/d/yyyy");
var pattern = "\\b\\d{1,2}/\\d{1,2}/\\d{4}\\b";
var header = DocumentApp.getActiveDocument().getHeader();
header.editAsText().replaceText(pattern, date);
}
-
You may get an error with this script if you do not already have any date string in the header.– DavidAug 15, 2017 at 20:51