<- c("2022-06-13", "2019-01-25", "2015-03-23", NA) str_vals
The vec_fmt_date()
function
Let’s create a character vector of dates in the ISO-8601 format for the next few examples:
Using vec_fmt_date()
(here with the "wday_month_day_year"
date style) will result in a character vector of formatted dates. Any NA
values remain as NA
values. The rendering context will be autodetected unless specified in the output
argument (here, it is of the "plain"
output type).
vec_fmt_date(str_vals, date_style = "wday_month_day_year")
[1] "Monday, June 13, 2022" "Friday, January 25, 2019"
[3] "Monday, March 23, 2015" NA
#> [1] "Monday, June 13, 2022" "Friday, January 25, 2019"
We can choose from any of 41 different date formatting styles. Many of these styles are flexible, meaning that the structure of the format will adapt to different locales. Let’s use the "yMMMEd"
date style to demonstrate this (first in the default locale of "en"
):
vec_fmt_date(str_vals, date_style = "yMMMEd")
[1] "Mon, Jun 13, 2022" "Fri, Jan 25, 2019" "Mon, Mar 23, 2015"
[4] NA
#> [1] "Mon, Jun 13, 2022" "Fri, Jan 25, 2019" "Mon, Mar 23, 2015" NA
Let’s perform the same type of formatting in the French ("fr"
) locale:
vec_fmt_date(str_vals, date_style = "yMMMEd", locale = "fr")
[1] "lun. 13 juin 2022" "ven. 25 janv. 2019" "lun. 23 mars 2015"
[4] NA
#> [1] "lun. 13 juin 2022" "ven. 25 janv. 2019" "lun. 23 mars 2015" NA
We can always use info_date_style()
to call up an info table that serves as a handy reference to all of the date_style
options.
As a last example, one can wrap the date values in a pattern with the pattern
argument. Note here that NA
values won’t have the pattern applied.
vec_fmt_date(str_vals, pattern = "Date: {x}")
[1] "Date: 2022-06-13" "Date: 2019-01-25" "Date: 2015-03-23" NA
#> [1] "Date: 2022-06-13" "Date: 2019-01-25" "Date: 2015-03-23" NA