Alex Rivera | Logout

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

Asked 2012-11-07T11:15:40.880
37

Is there any easy way for getting start date and end date of previous month from the current date in R?

I have only the current date. From it, i want to get the previous month, start date of previous month, end date of previous month.

currentDate<-Sys.Date() #return today's date as "2012-11-07"

I want the previous month start date as 2012-10-01 and end date as 2012-10-31 from today's date.

Edit
Report

2 Answers

43

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"
answered 2012-11-07T11:27:28.593
18

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"
answered 2012-11-07T15:17:17.463

Your Answer