Google-apps-script – Automatic date in Google Docs

dategoogle docsgoogle-apps-script

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?

Best Answer

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.