Find out the number of days of a month in R
The Hmisc library has a couple of helpful functions for doing this:
require(Hmisc)
monthDays(as.Date('2010-01-01'))
You can write simple function to do that:
numberOfDays <- function(date) {
m <- format(date, format="%m")
while (format(date, format="%m") == m) {
date <- date + 1
}
return(as.integer(format(date - 1, format="%d")))
}
Invoke as:
> date = as.Date("2011-02-23", "%Y-%m-%d")
> numberOfDays(date)
[1] 28
> date # date is unchanged
[1] "2011-02-23"
lubridate
package has required function "days_in_month" with respect to leapyears.
Your example:
date <- as.Date("2011-02-23", "%Y-%m-%d")
lubridate::days_in_month(date)
# Feb
# 28
Leap year (2016):
date_leap <- as.Date("2016-02-23", "%Y-%m-%d")
lubridate::days_in_month(date_leap)
# Feb
# 29