R Date Formatting
format() turns a date into text in a chosen layout. Codes inside the layout text say which parts of the date appear and how they look.
Format a date as text
The layout "%d %B %Y" asks for the day, the full month name and the year. The code %a adds the short weekday name at the front.
d <- as.Date("2024-01-31")
print(format(d, "%d %B %Y"))
print(format(d, "%a %d %B %Y"))Rearrange the parts with codes
The same date can print in a new order by moving the codes. The code %m prints the month as a number.
d <- as.Date("2024-01-31")
print(format(d, "%Y-%m-%d"))
print(format(d, "%m/%d/%Y"))Read the weekday and month names
weekdays() and months() pull one name out of a date. Each call returns one piece of text.
d <- as.Date("2024-01-31")
print(weekdays(d))
print(months(d))Parse a day-first date
The text 31/01/2024 puts the day first. The format argument tells as.Date() how to read it.
d <- as.Date("31/01/2024", format = "%d/%m/%Y")
print(d)
print(format(d, "%d %B %Y"))An impossible date becomes NA
February has no 31st day, so this text names no real date. The parse returns NA with no error, and is.na() shows the gap.
d <- as.Date("31/02/2024", format = "%d/%m/%Y")
print(d)
print(is.na(d))Example
d <- as.Date("05/03/2024", format = "%d/%m/%Y")
print(format(d, "%a %d %B %Y"))
print(months(d))
print(weekdays(d))Key points
- format() takes a date and a layout text and returns text.
- The code %d prints the day of the month as two digits.
- The code %B prints the full month name and %Y prints the four digit year.
- The code %a prints the short weekday name and %m prints the month number.
- weekdays() returns the full weekday name of a date and months() returns its full month name.
- as.Date() reads a day-first layout when its format argument names that layout.
- A date text that cannot exist returns NA when a format is given, and is.na() exposes the gap.
In this example a day-first text is parsed into a date. The date then prints with its short weekday name, and months() and weekdays() read its full names back.
Note
The name codes print English names in this course.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does format(d, "%B") return for a date in January?