Time difference in years with lubridate?
This is the lubridate
approach I would take:
interval(dob, today) / years(1)
Yields the answer of 32
years.
Note that the function will complain that it cannot express the remainder of the fraction of the year. This is because year is not a fixed concept, i.e. 366 in leap years and 365 in non-leap years. You can get an answer with more detail in regard to the number of weeks and days:
interval_period = interval(dob, today)
full_year = interval_period %/% years(1)
remaining_weeks = interval_period %% years(1) %/% weeks(1)
remaining_days = interval_period %% years(1) %% weeks(1) %/% days(1)
sprintf('Your age is %d years, %d weeks and %d days', full_year, remaining_weeks, remaining_days)
# [1] "Your age is 32 years, 51 weeks and 1 days"
Note that I use %/%
for division and %%
as modulo to get the remaining weeks/days after subtracting the full years/weeks.
as.duration(interval(dob,today)) %/% as.duration(years(1))
should do the job without errors.
This is an old question, but I still missing the following clean approach. (Tidyverse is only necessary for the %>%
operator.)
library(tidyverse)
library(lubridate)
today<-mdy(08312015)
dob<-mdy(09071982)
interval(dob, today) %>%
as.numeric('years')
# 32.98015 - you have to decide how to deal with the fraction of a year