5.6 Format Dates

20220108

A human readable way of formatting a date is with the lubridate::stamp() function. It takes a string argument as a template and looks for a date in there and then generates a function that uses base::format() to format the date within the template string.

stamp('The best day was 17 Jan 1999')

The function can be applied to an argument to format the supplied date using the template:

stamp('The best day was 17 Jan 1999', quiet=TRUE)(today())
## [1] "The best day was 21 Nov 2024"

Essentially, the above code uses lubridate::stamp() to create a function that will do the following base::format():

format(today(), format="The best day was %d %b %Y")
## [1] "The best day was 21 Nov 2024"

To get rid of a leading 0 in the day (i.e., 8 instead of 08) we can add a - to the format:

format(ymd("20220108"), format="The best day was %d %b %Y")
## [1] "The best day was 08 Jan 2022"
format(ymd("20220108"), format="The best day was %-d %b %Y")
## [1] "The best day was 8 Jan 2022"


Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0