R difftime() Function - Computing Time Differences
The R difftime() function is used to compute the difference between two dates/times.
difftime() can specify the unit of the returned time difference, such as days, hours, minutes, and so on.
The syntax of the difftime() function is as follows:
difftime(time1, time2, units = c("auto", "secs", "mins", "hours", "days", "weeks"))
Parameter Description:
-
time1, time2 A date-time object.
-
units The time unit of the returned difference.
Example
Two dates
start_date
<-
as.Date
(
"2026-01-01"
)
end_date
<-
as.Date
(
"2026-05-11"
)
Compute the difference (in days by default)
diff_days
<-
difftime
(
end_date, start_date
)
(
paste
(
"Days Difference:"
, diff_days
)
)
Specify the unit as weeks
diff_weeks
<-
difftime
(
end_date, start_date,
units
=
"weeks"
)
(
paste
(
"Week difference:"
,
round
(
diff_weeks,
1
)
)
)
Date Comparison
dates
<-
as.Date
(
c
(
"2025-06-15"
,
"2026-01-01"
,
"2026-05-11"
,
"2026-12-31"
)
)
reference
<-
as.Date
(
"2026-05-11"
)
diffs
<-
difftime
(
dates, reference,
units
=
"days"
)
(
"Day difference between each date and today:"
)
(
diffs
)
The output of the code above is:
[1] "相差天数: 130"
[1] "相差周数: 18.6"
[1] "各日期与今天的天数差:"
Time differences in days
[1] -330 -130 0 234
R Language Examples