Finding previous month end date

1.6k views Asked by At

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.

3

There are 3 answers

2
Gregor Thomas On BEST ANSWER

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"
4
r2evans On

The integer units of Date are days, so you can do:

seq.Date(from=as.Date("2018-10-31"), length=2, by="-1 months") - c(0,1)
# [1] "2018-10-31" "2018-09-30"

If you want arbitrary prior-last-date:

(d <- as.POSIXlt(Sys.Date()))
# [1] "2018-11-08 UTC"
d$mday <- 1L
as.Date(d) - 1
# [1] "2018-10-31"

Replace Sys.Date() with whatever single date you have. If you want to vectorize this:

(ds <- Sys.Date() + c(5, 20, 50))
# [1] "2018-11-13" "2018-11-28" "2018-12-28"
lapply(as.POSIXlt(ds), function(a) as.Date(`$<-`(a, "mday", 1L)) - 1L)
# [[1]]
# [1] "2018-10-31"
# [[2]]
# [1] "2018-10-31"
# [[3]]
# [1] "2018-11-30"
2
Jiaxiang On

I don't use function chron. But I think the function duration from lubridate helps you. You don't need use floor_date to confuse you.

library(lubridate)
#> 
#> 载入程辑包:'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
library(tidyverse)
better_date <- 
    str_split("10/31/2018",'/') %>% 
    .[[1]] %>% 
    .[c(3,1,2)] %>% 
    str_flatten(collapse = '-') %>% 
    as.Date()
(better_date - duration('1 months')) %>% 
    as.Date()
#> [1] "2018-09-30"

Created on 2018-11-09 by the reprex package (v0.2.1)