How to calculate time differences in R

how-to
dates
Learn calculate time differences in r with clear examples and explanations.
Published

March 26, 2026

Introduction

Working with dates in R often requires calculating the time difference between two dates. The lubridate package (part of tidyverse) provides powerful functions like time_length() and interval() that make it easy to calculate precise durations in different units. This is essential for data analysis involving time series, age calculations, or any temporal comparisons.

library(tidyverse)
library(lubridate)

Basic Date Subtraction

Let’s start by creating two date objects and exploring basic date arithmetic. We’ll use dates from 2014 and 2015 to see how R handles date differences.

date1 <- as.Date("2014-01-01")
date2 <- as.Date("2015-12-31")
date1
date2

When we subtract dates in R, the result is a “difftime” object that shows the difference in days. Notice how the order of subtraction affects the sign of the result.

date1 - date2
date2 - date1

The first calculation gives us a negative value because we’re subtracting a later date from an earlier one, while the second gives us a positive value representing 729 days.

Using time_length() for Flexible Units

The time_length() function from lubridate allows us to convert date differences into various time units. Let’s convert our date difference into days first.

time_length(date2 - date1, unit = "days")

This gives us the same result as basic subtraction but in a cleaner numeric format. Now let’s see the same duration expressed in years.

time_length(date2 - date1, unit = "years")

The result shows approximately 1.996 years, which makes sense since we’re spanning nearly two full years.

Converting to Other Time Units

We can easily convert our date difference to months or weeks using the same function. This flexibility makes time_length() very useful for different analytical needs.

time_length(date2 - date1, unit = "months")
time_length(date2 - date1, unit = "weeks")

The months calculation shows about 23.97 months, while weeks gives us approximately 104.14 weeks.

Using Intervals for More Precision

The interval() function creates a more precise time span object that can account for leap years and varying month lengths. This is particularly useful for exact calculations.

int <- interval(date1, date2)
time_length(int, "years")

Using intervals provides the most accurate calculations, especially important when working with longer time periods or when precision matters for your analysis.

Summary

Calculating time differences in R is straightforward with lubridate’s time_length() and interval() functions. Basic date subtraction works for simple cases, but time_length() offers flexibility in units, while interval() provides the highest precision. Choose the method that best fits your analytical needs and required precision level.