Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R format() Function - Date Formatting

R format() Function - Date Formatting

R Language Examples R Language Examples

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:

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

print

(

format

(

today,

"%Y year %m month %d day"

)

)

print

(

format

(

today,

"%B %d, %Y"

)

)

print

(

format

(

today,

"%A"

)

)

print

(

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"

)

print

(

"Month names:"

)

print

(

months

)

The output of the code above is:

[1] "2026 年 05 月 11 日"

[1] "五月 11, 2026"

[1] "星期一"

[1] "今年第 131 天"

[1] "月份名:"

[1] "一月"   "五月"   "十二月"

R Language Examples R Language Examples