R as.Date() Function - Date Conversion
The R as.Date() function is used to convert character data to date type.
The date type is the basis for handling time series data in R, supporting addition, subtraction, and comparison.
The syntax of the as.Date() function is as follows:
as.Date(x, format = "%Y-%m-%d")
Parameter Description:
-
x A character date string.
-
format A date format string.
| Format specifier | 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"
)
(
date1
)
(
paste
(
"Type:"
,
class
(
date1
)
)
)
Non-standard format
date2
<-
as.Date
(
"11/05/2026"
,
format
=
"%d/%m/%Y"
)
(
date2
)
date3
<-
as.Date
(
"May 11, 2026"
,
format
=
"%B %d, %Y"
)
(
date3
)
Date arithmetic
today
<-
as.Date
(
"2026-05-11"
)
future
<-
today
30
(
paste
(
"30 Days Later:"
, future
)
)
(
paste
(
"Days Difference:"
,
as.numeric
(
future
today
)
)
)
The output of the code above is:
[1] "2026-05-11"
[1] "类型: Date"
[1] "2026-05-11"
[1] "2026-05-11"
[1] "30 天后: 2026-06-10"
[1] "相差天数: 30"
R Language Examples