The lubridate
function %m+%
may be useful here:
Add and subtract months to a date without exceeding the last day of the new month
as.Date("2014-12-31") %m+% months(6)
# [1] "2015-06-30"
To also handle the second case, you will need to round up to nearest month using ceiling_date
, and subtract one day using days
.
ceiling_date(as.Date("2014-02-28") %m+% months(6), unit = "month") - days(1)
# [1] "2014-08-31"