Kyoto
Kyoto

Reputation: 53

End of the (next) month from a random date

I have a question what is the fastest way to get end of the month from a day. I have a really large table and I want my code to be fast. My current code looks as follows:

library(lubridate)

end_of_month <- function(date){
 day(date) <- days_in_month(date)
 date
}

I have another question. Is it a fast way to get a last day of the next month from a random date?

"2019-05-15" %>% as.Date() %m+% months(1) %>% end_of_month  # 2019-06-30

Can I do this in one step or do I need an extra function to handle this?

Upvotes: 2

Views: 146

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

Updated answer

Thanks to @Edward for pointing out the issue in the original answer.

You can use ceiling_date after adding 1 month to the original date

ceiling_date(as.Date('2019-05-15') + months(1), unit = "month") - 1
#[1] "2019-06-30"

ceiling_date(as.Date('2019-04-15') + months(1), unit = "month") - 1
#[1] "2019-05-31"

Old Answer

We can use ceiling_date with unit as '2 months'

library(lubridate)
'2019-05-15' %>% as.Date() %>% ceiling_date(unit = '2 months') - 1
#[1] "2019-06-30"

Upvotes: 5

Related Questions