R as.Date() Function - Date Conversion
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 code | Meaning | Example |
|---|---|---|
| %Y | Four-digit year | 2026 |
| %y | Two-digit year | 26 |
| %m | Month (01-12) | 05 |
| %d | Day (01-31) | 11 |
| %B | Full month name | May |
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)))
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"Other Extensions
R Language Examples