4.8 Update the date automatically

If you want the date on which the Rmd document is compiled to be reflected in the output report, you can add an inline R expression to the date field in YAML, and use the Sys.Date() or Sys.time() function to obtain the current date, e.g.,

  1. date: "`r Sys.Date()`"

You may want to specify the desired date or date-time format to make it more human-readable, e.g.,

  1. date: "`r format(Sys.time(), '%d %B, %Y')`"

This will generate the date dynamically each time you knit your document, e.g., 23 November, 2020. If you wish to customize the format of the dates, you can alter the time format by providing your own format string. Here are some examples:

  • %B %Y: November 2020
  • %d/%m/%y: 23/11/20
  • %a/%d/%b: Mon 23 Nov

A full table of POSIXct formats is shown in Table 4.1.

TABLE 4.1: Date and time formats in R.
CodeMeaningCodeMeaning
%aAbbreviated weekday%AFull weekday
%bAbbreviated month%BFull month
%cLocale-specific date and time%dDecimal date
%HDecimal hours (24 hour)%IDecimal hours (12 hour)
%jDecimal day of the year%mDecimal month
%MDecimal minute%pLocale-specific AM/PM
%SDecimal second%UDecimal week of the year (starting on Sunday)
%wDecimal Weekday (0=Sunday)%WDecimal week of the year (starting on Monday)
%xLocale-specific Date%XLocale-specific Time
%y2-digit year%Y4-digit year
%zOffset from GMT%ZTime zone (character)

As a final note, you may also want to include some explanatory text along with the date. You can add any text such as “Last compiled on” before the R code as follows:

  1. date: "Last compiled on `r format(Sys.time(), '%d %B, %Y')`"