Skip to contents

Calculates the duration of time between two provided date objects. Supports vectorized data (i.e. dplyr::mutate()).

Usage

calc_duration(x, y, units = NULL)

Arguments

x

A date or datetime. The start date(s)/timestamp(s).

y

A date or datetime. The end date(s)/timestamp(s).

units

A character. Units of the returned duration (i.e. 'seconds', 'days', 'years').

Value

If 'units' specified, returns numeric. If 'units' unspecified, returns an object of class 'Duration'.

Note

Supports multiple calculations against a single time point (i.e. multiple start dates with a single end date). Note that start and end must otherwise be of the same length.

When the start and end dates are of different types (i.e. x = date, y = datetime), a lossy cast will be performed which strips the datetime data of its time components. This is done to avoid an assumption of more time passing that would otherwise come with casting the date data to datetime.

Examples

library(lubridate)
#> Loading required package: timechange
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
library(purrr)

# Dates -> duration in years
calc_duration(
  x = mdy(map_chr(sample(1:9, 5), ~ paste0('01/01/199', .x))),
  y = mdy(map_chr(sample(1:9, 5), ~ paste0('01/01/200', .x))),
  units = 'years'
)
#> [1] 12.999316  6.001369 12.000000  6.001369 11.000684

# datetimes -> durations
calc_duration(
  x = mdy_hm(map_chr(sample(1:9, 5), ~ paste0('01/01/199', .x, ' 1', .x, ':00'))),
  y = mdy_hm(map_chr(sample(1:9, 5), ~ paste0('01/01/200', .x, ' 0', .x, ':00')))
)
#> [1] "283957200s (~9 years)"  "347122800s (~11 years)" "126172800s (~4 years)" 
#> [4] "347122800s (~11 years)" "378662400s (~12 years)"

# Mixed date classes -> durations
calc_duration(
  x = mdy(map_chr(sample(1:9, 5), ~ paste0('01/01/199', .x))),
  y = mdy_hm(map_chr(sample(1:9, 5), ~ paste0('01/01/200', .x, ' 0', .x, ':00')))
)
#> [1] "378720000s (~12 years)" "220932000s (~7 years)"  "126234000s (~4 years)" 
#> [4] "378712800s (~12 years)" "568112400s (~18 years)"