2

I have dates of format 2015-03 (i.e year-month). Now I want to calculate the month difference in between 2 dates.

Example: difference between dates 2015-03 and 2014-12 should be 3 or 4 as December to March is 3 months or 4 months depending on whether we consider December or not.

talat
  • 68,970
  • 21
  • 126
  • 157
pranav
  • 1,041
  • 1
  • 10
  • 11
  • 3
    possible duplicate of [Get the difference between dates in terms of weeks, months, quarters, and years](http://stackoverflow.com/questions/14454476/get-the-difference-between-dates-in-terms-of-weeks-months-quarters-and-years) – Frank Schmitt Sep 15 '15 at 10:47

2 Answers2

5

You can do it via diff

require(lubridate)
a <- c("2015-03","2014-12")
a_parsed <- ymd(paste0(a,"-01")) # There might be a nicer solution to get the dates

diff(year(a_parsed)) * 12 + diff(month(a_parsed)) # Results in 3

Use + 1 to "consider December"

Explanation:
diff(year(a_parsed)) gives you the difference in the years, * 12 the month resulting from this. diff(month(a_parsed)) results in the monthly difference, ignoring the yearly difference. Combined it results in the Monthly difference you asked for.

Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • thank you Floo0, though I used strptime according to my code and variable.....I did use your idea :) – pranav Sep 15 '15 at 11:47
1
a <- "2015-03"
b <- "2014-12"
a <- unlist(strsplit(a, "-"))
b <- unlist(strsplit(b, "-"))
a <- (as.numeric(a[1])*12) + as.numeric(a[2])
b <- (as.numeric(b[1])*12) + as.numeric(b[2])
difference <- diff(c(b,a))
difference

The result of this is 3

Will
  • 148
  • 2
  • 12