R as.Date() Function - Date Conversion

R 语言实例R Language Examples

The R as.Date() function is used to convert character data to date type.

Date type is the basis for handling time series data in R, supporting addition/subtraction operations and comparisons.

The syntax format of the as.Date() function is as follows:

as.Date(x, format = "%Y-%m-%d")

Parameter description:

  • xCharacter date string.

  • formatDate format string.

Format codeMeaningExample
%YFour-digit year2026
%yTwo-digit year26
%mMonth (01-12)05
%dDay (01-31)11
%BFull month nameMay

Example

# Standard format conversion
date1 <- as.Date("2026-05-11")
print(date1)
print(paste("Type:", class(date1)))

# Non-standard format
date2 <- as.Date("11/05/2026", format = "%d/%m/%Y")
print(date2)

date3 <- as.Date("May 11, 2026", format = "%B %d, %Y")
print(date3)

# Date arithmetic
today <- as.Date("2026-05-11")
future <- today + 30
print(paste("After 30 days:", future))
print(paste("Difference in days:", as.numeric(future - today)))

The output of executing the above code is:

[1] "2026-05-11"
[1] "类型: Date"
[1] "2026-05-11"
[1] "2026-05-11"
[1] "30 天后: 2026-06-10"
[1] "相差天数: 30"

R 语言实例R Language Examples

Other Extensions