R format() Function - Date Formatting

R 语言实例R Language Examples

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 specifiersDescriptionOutput example
%Y-%m-%dYear-month-day2026-05-11
%B %d, %YMonth day, yearMay 11, 2026
%AFull weekday nameMonday
%aWeekday abbreviationMon
%bMonth abbreviationMay
%jDay of the year131

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)

The output of the above code is:

[1] "2026 年 05 月 11 日"
[1] "五月 11, 2026"
[1] "星期一"
[1] "今年第 131 天"
[1] "月份名:"
[1] "一月"   "五月"   "十二月"

R 语言实例R Language Examples

Other extensions