rdate

How do I find the first and last day of next month?


If I have a given date, how do I find the first and last days of the next month?

For example,

today <- as.Date("2009-04-04")

I want to find

# first date in next month
"2009-05-01"  

# last date in next month
"2009-05-31"

Solution

  • You can do this with base R:

    today <- as.Date("2009-04-04")
    
    first <- function(x) {
      x <- as.POSIXlt(x)
      x$mon[] <- x$mon + 1
      x$mday[] <- 1
      x$isdst[] <- -1L
      as.Date(x)
    }
    
    first(today)
    #[1] "2009-05-01"
    
    first(first(today)) - 1
    #[1] "2009-05-31"