0

I'm running into some strange behavior when using lubridate

dtStart<-ymd(20000430)
n<-24
dtStart %m+% months(0:n)

I'm expecting 24 month end dates, but I get the 30th of every month, including those months where there are 31 days:

[1] "2000-04-30 UTC" "2000-05-30 UTC" "2000-06-30 UTC" "2000-07-30 UTC" "2000-08-30 UTC" "2000-09-30 UTC" "2000-10-30 UTC" "2000-11-30 UTC" "2000-12-30 UTC"
[10] "2001-01-30 UTC" "2001-02-28 UTC" "2001-03-30 UTC" "2001-04-30 UTC" "2001-05-30 UTC" "2001-06-30 UTC" "2001-07-30 UTC" "2001-08-30 UTC" "2001-09-30 UTC"
[19] "2001-10-30 UTC" "2001-11-30 UTC" "2001-12-30 UTC" "2002-01-30 UTC" "2002-02-28 UTC" "2002-03-30 UTC" "2002-04-30 UTC"

Thanks for any advice on solving this using lubridate? (Not base R)

csrvermaak
  • 278
  • 1
  • 2
  • 13
  • Possible duplicate of [How do you generate a sequence of the last day of the month over two years in R?](http://stackoverflow.com/questions/8333838/how-do-you-generate-a-sequence-of-the-last-day-of-the-month-over-two-years-in-r) – Rentrop Nov 24 '15 at 15:29
  • The question was specified as using lubridate, the possible duplicate uses base R. – csrvermaak Nov 24 '15 at 16:03

2 Answers2

0

You're not really asking the last day but to "add and subtract months to a date without exceeding the last day of the new month" so the function is behaving exactly as expected.

Anyway, you can "trick" it a bit to get what you want by giving it a start date from a month that has the max number of days a month can have (31) and modifying the call accordingly:

dtStart<-ymd(20000331)
dtStart %m+% months(1:(n+1))
# [1] "2000-04-30 UTC" "2000-05-31 UTC" "2000-06-30 UTC" "2000-07-31 UTC" "2000-08-31 UTC" "2000-09-30 UTC" "2000-10-31 UTC"
# [8] "2000-11-30 UTC" "2000-12-31 UTC" "2001-01-31 UTC" "2001-02-28 UTC" "2001-03-31 UTC" "2001-04-30 UTC" "2001-05-31 UTC"
# [15] "2001-06-30 UTC" "2001-07-31 UTC" "2001-08-31 UTC" "2001-09-30 UTC" "2001-10-31 UTC" "2001-11-30 UTC" "2001-12-31 UTC"
# [22] "2002-01-31 UTC" "2002-02-28 UTC" "2002-03-31 UTC" "2002-04-30 UTC"
Cath
  • 23,906
  • 5
  • 52
  • 86
0

Answer:

ceiling_date(dtStart %m+% months(0:n),unit = "month")-days(1)

This code does a ceiling_date to the next month, and then subtract a day to find the last dat of the month.

csrvermaak
  • 278
  • 1
  • 2
  • 13