R format() Function - Date Formatting
The R format() function is used to convert a date object into a string in 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:
-
x A date object (Date or POSIXct).
-
format The target 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 | Abbreviated weekday name | Monday |
| %b | Abbreviated month name | May |
| %j | Day of the year | 131 |
Example
today
<-
as.Date
(
"2026-05-11"
)
Various formats
(
format
(
today,
"%Y year %m month %d day"
)
)
(
format
(
today,
"%B %d, %Y"
)
)
(
format
(
today,
"%A"
)
)
(
paste
(
"Day "
,
format
(
today,
"%j"
)
,
" of the year"
)
)
Process a date vector
dates
<-
as.Date
(
c
(
"2026-01-01"
,
"2026-05-11"
,
"2026-12-31"
)
)
months
<-
format
(
dates,
"%B"
)
(
"Month names:"
)
(
months
)
The output of the code above is:
[1] "2026 年 05 月 11 日"
[1] "五月 11, 2026"
[1] "星期一"
[1] "今年第 131 天"
[1] "月份名:"
[1] "一月" "五月" "十二月"
R Language Examples