R format.Date
Format the same calendar date as a four-digit year, two-digit month, and two-digit day.
A simple example
format.Date
- Start with January 2, 2024
- Do this Format year/month/day
- Result 2024/01/02
Syntax
format(as.Date("2024-02-29"), "%Y/%m/%d")
Run these examples in R
Save one example at a time as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.RPrint a consistent date on a receipt
An office prints dates on receipts or billing records that may cross a month boundary. Use calendar-aware date handling and a consistent representation so the displayed date can be read back unambiguously.
cat(format(as.Date("2024-02-29"), "%Y/%m/%d"), "\n", sep = "")
2024/02/29
The date is February 29. Padding the month and day keeps the receipt layout consistent.
Name a concert recording
The school archive sorts dates in file names. Render the already validated date as year-month-day, using two digits for both month and day.
Label an exhibition proof
A printer needs a date stamp that sorts correctly in a list. Render the already validated date as year-month-day, using two digits for both month and day.
What to watch for
Formatting changes only the displayed text. Keep a date value for later calculations.