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.,
date: "`r Sys.Date()`"
You may want to specify the desired date or date-time format to make it more human-readable, e.g.,
date: "`r format(Sys.time(), '%d %B, %Y')`"
This will generate the date dynamically each time you knit your document, e.g., 17 September, 2024. 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
: September 2024%d/%m/%y
: 17/09/24%a/%d/%b
: Tue 17 Sep
A full table of POSIXct formats is shown in Table 4.1.
Code | Meaning | Code | Meaning |
---|---|---|---|
%a | Abbreviated weekday | %A | Full weekday |
%b | Abbreviated month | %B | Full month |
%c | Locale-specific date and time | %d | Decimal date |
%H | Decimal hours (24 hour) | %I | Decimal hours (12 hour) |
%j | Decimal day of the year | %m | Decimal month |
%M | Decimal minute | %p | Locale-specific AM/PM |
%S | Decimal second | %U | Decimal week of the year (starting on Sunday) |
%w | Decimal Weekday (0=Sunday) | %W | Decimal week of the year (starting on Monday) |
%x | Locale-specific Date | %X | Locale-specific Time |
%y | 2-digit year | %Y | 4-digit year |
%z | Offset from GMT | %Z | Time 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:
date: "Last compiled on `r format(Sys.time(), '%d %B, %Y')`"