I was about to say that's simple, but difftime() stops at weeks. How odd.
So one possible answer would be to hack something up:
# turn a date into a 'monthnumber' relative to an origin
R> monnb <- function(d) { lt <- as.POSIXlt(as.Date(d, origin="1900-01-01")); \
lt$year*12 + lt$mon }
# compute a month difference as a difference between two monnb's
R> mondf <- function(d1, d2) { monnb(d2) - monnb(d1) }
# take it for a spin
R> mondf(as.Date("2008-01-01"), Sys.Date())
[1] 24
R>
Seems about right. One could wrap this into some simple class structure. Or leave it as a hack :)
Edit: Also seems to work with your examples from the Mathworks:
Adding the EndOfMonth flag is left as an exercise to the reader :)
Edit 2: Maybe difftime leaves it out as there is no reliable way to express fractional difference which would be consistent with the difftime behavior for other units.
To me it makes sense to think about this problem as simply subtracting two dates, and since minuend − subtrahend = difference (wikipedia), I put the later date first in the parameter list.
Note that it works fine for dates preceeding 1900 despite those dates having internal representations of year as negative, thanks to the rules for subtracting negative numbers...
This calculates the number of whole months between the two dates. Remove the -1 if you want to include the current month/ remainder that isn't a whole month.
mos(20150101,20150228) # 1
mos(20150131,20150228) # 0
# you can use "20150101" instead of 20150101
mob(20150131,20150228) # 1
mob(20150131,20150228) # 1
# you can use a format of "20150101", 20150101, 201501
Lubridate [package] provides tools that make it easier to parse and manipulate dates. These tools are grouped below by common purpose. More information about each function can be found in its help documentation.
interval {lubridate} creates an Interval-class object with the specified start and end dates. If the start date occurs before the end date, the interval will be positive. Otherwise, it will be negative
today {lubridate} The current date
months{Base} Extract the month These are generic functions: the methods for the internal date-time classes are documented here.
%/% {base} indicates integer division AKA ( x %/% y ) (up to rounding error)
You can use as.yearmon() function from zoo package. This function converts a Date type variable to a year-month type variable. You can subtract two year-month type variables and then multiple by 12 to get diff in months as follows: