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

R as.Date() Function - Date Conversion

R as.Date() Function - Date Conversion

R Language Examples R Language Examples

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:

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"

)

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

(

"30 Days Later:"

, future

)

)

print

(

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 R Language Examples