Is there a way to convert below time difference in terms of years and months?
as.Date(Sys.Date()) - as.Date("2015-08-20")
Time difference of 2753 days
Expected output (Since it app.. around 7 years and 5 months?
7.5
Is there a way to convert below time difference in terms of years and months?
as.Date(Sys.Date()) - as.Date("2015-08-20")
Time difference of 2753 days
Expected output (Since it app.. around 7 years and 5 months?
7.5
You may try the below code
library(lubridate)
months <- time_length(as.numeric(difftime(as.Date(Sys.Date()) , as.Date("2015-08-20"), units = 'days')), 'month')
years <- time_length(as.numeric(difftime(as.Date(Sys.Date()) , as.Date("2015-08-20"), units = 'days')), 'year')
A trick using only base R is to add the difftime
on to the first of January in the year 0 AD (this exists in R even if it didn't technically exist in reality).
The resulting date is the number of years, months and days of the difftime (with an extra day, which is easy to subtract)
(as.POSIXct('0000-01-01') + (as.Date(Sys.Date()) - as.Date("2015-08-20"))) |>
as.character() |>
strsplit('-') |>
getElement(1) |>
as.numeric() |>
setNames(c('years', 'months', 'days')) - c(0, 0, 1)
#> years months days
#> 7 7 15
Created on 2023-03-04 with reprex v2.0.2