0

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  
manu p
  • 952
  • 4
  • 10
  • 1
    duplicate? https://stackoverflow.com/a/15569373/13513328 – Waldi Mar 04 '23 at 17:37
  • 1
    Does this answer your question? [Get date difference in years (floating point)](https://stackoverflow.com/questions/15569333/get-date-difference-in-years-floating-point) – GuedesBF Mar 04 '23 at 18:36
  • Did you mean years and fraction of a year as there is about 7.5 years between those dates but there is not 7 years and 5 months? – G. Grothendieck Mar 05 '23 at 14:53

2 Answers2

0

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')
jkatam
  • 2,691
  • 1
  • 4
  • 12
0

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87