In this tutorial we will learn how to find the difference between two date objects in R in terms of days, months, and years. We will learn how to use time_length() function available in tidyverse as part of lubridate package to get the difference as dyas, weeks, months, and years.
library(tidyverse) ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ── ✔ dplyr 1.1.4 ✔ readr 2.1.5 ✔ forcats 1.0.0 ✔ stringr 1.5.1 ✔ ggplot2 3.5.1 ✔ tibble 3.2.1 ✔ lubridate 1.9.3 ✔ tidyr 1.3.1 ✔ purrr 1.0.2 ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ── ✖ dplyr::filter() masks stats::filter() ✖ dplyr::lag() masks stats::lag() ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to beco
Let us create two date variables using as.Date() function.
date1 <- as.Date("2014-01-01") date2 <- as.Date("2015-12-31")
And here is how our date variable looks like.
date1 [1] "2014-01-01"
date2 [1] "2015-12-31"
Difference between two dates in days
We can find the difference between two dates in terms of the number of days, by using subtraction. In the example below date1 precedes date2, therefore we get the number of days as negative.
date1 - date2 Time difference of -729 days
By subtracting date1 from date2, we will get the difference in terms days as we would like.
date2 - date1 Time difference of 729 days
We can also use the function time_length() function with unit=”days” as argument to get the number of days between two dates.
time_length(date2-date1, unit="days") [1] 729
Difference between two dates in years
With time_length() function using unit=”years” as argument we will get the number of years between two dates. Note that the result we get is a float and we can round it to get the number of years as integer.
time_length(date2-date1, unit="years") [1] 1.995893
Difference between two dates in months
Using unit=”months” as argument to time_length() function as shown below we get the number of months between the two dates as a float.
time_length(date2-date1, unit="months") [1] 23.95072
Difference between two dates in weeks
Similarly, using unit=”weeks” as argument to time_length() function, we get the time difference between two dates in weeks.
time_length(date2-date1, unit="weeks") [1] 104.1429