Search code examples
rdateseqchron

Finding previous month end date


From date 10/31/2018, I want to obtain 09/30/2018.

I tried:

PREV.PROD.DATE<-seq.Date(from=as.Date(chron("10/31/2018")),length=2,by="-1 months")

but it returns:

"2018-10-31" "2018-10-01"

How can I obtain 09/30 instead of 10/01?

Notes: I would like to avoid to use an external package, and I would like the solution to work for any end of month date.


Solution

  • I like to floor the date - making it the first day of its month, and then subtract 1 to make it the last day of the previous month:

    x = as.Date("2018-10-31")
    library(lubridate)
    floor_date(x, unit = "months") - 1
    # [1] "2018-09-30"
    

    Here's a version without using other packages:

    as.Date(format(x, "%Y-%m-01")) - 1
    # [1] "2018-09-30"