Getting previous month start date and end date from current date in R

Another option with lubridate package is to use the rollback function, that as the description says, do exactly that.

rollback changes a date to the last day of the previous month or to the first day of the month. Optionally, the new date can retain the same hour, minute, and second information.

library(lubridate)

currentDate <- Sys.Date()

end_last_month <- rollback(currentDate)

init_last_month <- rollback(end_last_month, roll_to_first = TRUE)

Using lubridate it's a piece of cake:

library(lubridate)
floor_date(Sys.Date() - months(1), "month")

There is a plenty of good libraries in R. Seems like everything you need is already created.

UPDATED version:

library(lubridate)
floor_date(as.Date("2011-03-29"), "month") - months(1)

This one is corrected to work well with the 29th of march.


You can use the library lubridate, which is very good at doing date arithmetic.

library(lubridate)

currentDate <-Sys.Date()
# end of previous month:
eopm <- currentDate - days(day(currentDate))
# [1] "2012-10-31"

# start of previous month:
sopm <- currentDate - days(day(currentDate))
sopm <- sopm - days(day(sopm) - 1)
# [1] "2012-10-01"

A number of packages have handy date functions, but to roll your own:

A start of month function:

som <- function(x) {
  as.Date(format(x, "%Y-%m-01"))
}

and an end of month function (although you won't need this here):

eom <- function(x) {
  som(som(x) + 35) - 1
}

That should get you going. For example, to get the end of the previous month:

som(Sys.Date()) - 1
[1] "2012-10-31"

and the start of the month:

som(som(Sys.Date()) - 1)
[1] "2012-10-01"

Tags:

Date

R