Find out the number of days of a month in R

I have a date in P

 date = as.Date("2011-02-23", "%Y-%m-%d")

Is it possible to find out the number of days of the month of that particular date? (With respect to leapyears). In PHP it would look similar to this (http://www.php.net/manual/en/function.date.php):

days = format(date, "%t")

but "%t" seems to have a different meaning in R. Is there a solution for this problem?


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

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"

That is as easy as taking a difference between two dates -- so make it the first of the month and the following month:

R> difftime( as.Date("2011-06-01"), as.Date("2011-05-01") )
Time difference of 31 days
R> as.numeric(difftime( as.Date("2011-06-01"), as.Date("2011-05-01") ))
[1] 31
R> 

The as.numeric() casts this to a number you can use.


Here are a couple of approaches. Both approaches are vectorized, i.e. the input x can be a single "Date" class date or a vector of such dates.

1) This converts the input date, x, into a "yearmon" object and then converts it back to the last of the month and first of the month and subtracts the two adding 1.

x <- Sys.Date() # use today as the test date

library(zoo)
ym <- as.yearmon(x)
as.Date(ym, frac = 1) - as.Date(ym) + 1
## Time difference of 30 days

or for a numeric result use:

as.numeric(as.Date(ym, frac = 1) - as.Date(ym) + 1)
## [1] 30

1a) A variation would be:

as.Date(ym + 1/12) - as.Date(ym)
## Time difference of 30 days

or for a numeric result:

as.numeric(as.Date(ym + 1/12) - as.Date(ym))
## [1] 30

2) This is a base solution. First we define fom which inputs a "Date" vector and returns the first of the month of each component. Now we just take the difference between the first of the next month and the first of the current month.

fom <- function(x) as.Date(cut(x, "month"))
fom1 <- fom(x)
fom2 <- fom(fom1 +  32)
as.numeric(fom2 - fom1)
## [1] 30