R format() Function - Date Formatting
The R format() function is used to convert date objects into strings of a specified format.
format() can display dates in various human-readable forms.
The syntax of the format() function is as follows:
format(x, format = "%Y-%m-%d")
Parameter description:
xDate object (Date or POSIXct).
formatTarget format string.
| Common format specifiers | Description | Output example |
|---|---|---|
| %Y-%m-%d | Year-month-day | 2026-05-11 |
| %B %d, %Y | Month day, year | May 11, 2026 |
| %A | Full weekday name | Monday |
| %a | Weekday abbreviation | Mon |
| %b | Month abbreviation | May |
| %j | Day of the year | 131 |
Example
today <- as.Date("2026-05-11")
# Various formats
print(format(today, "%Y-%m-%d"))
print(format(today, "%B %d, %Y"))
print(format(today, "%A"))
print(paste("Day ", format(today, "%j"), " of the year"))
# Handling date vectors
dates <- as.Date(c("2026-01-01", "2026-05-11", "2026-12-31"))
months <- format(dates, "%B")
print("Month names:")
print(months)
# Various formats
print(format(today, "%Y-%m-%d"))
print(format(today, "%B %d, %Y"))
print(format(today, "%A"))
print(paste("Day ", format(today, "%j"), " of the year"))
# Handling date vectors
dates <- as.Date(c("2026-01-01", "2026-05-11", "2026-12-31"))
months <- format(dates, "%B")
print("Month names:")
print(months)
The output of the above code is:
[1] "2026 年 05 月 11 日" [1] "五月 11, 2026" [1] "星期一" [1] "今年第 131 天" [1] "月份名:" [1] "一月" "五月" "十二月"Other extensions
R Language Examples