0

Given any date, I use this code to get the beginning date of previous month from that date:

library(lubridate)

end_date <- '2021-10-30'
floor_date(as.Date(end_date) - months(1), 'month')
[1] "2021-09-01"

But I've found it return NA, as the format of date is %Y-%m-31:

end_date <- '2021-10-31'
floor_date(as.Date(end_date) - months(1), 'month')
[1] NA

How could we explain this error?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
ah bon
  • 9,293
  • 12
  • 65
  • 148
  • 1
    I guess it's because there is no 31st of September. Try with `'2021-08-31'`, it works well. – Maël Jan 19 '22 at 08:50
  • Sorry, I don't think so, if you check: https://www.wincalendar.com/Calendar/Date/October-31-2021 – ah bon Jan 19 '22 at 08:52
  • It seems not answer my question from the link you provided, since the error comes from not how to get the first day, but previous month @Limey – ah bon Jan 19 '22 at 08:58
  • 2
    Your error is explained by the fact that `as.Date(2021-10-31) - months(1)` would return `2021-09-31` but since this day does not exist it returns NA. – Maël Jan 19 '22 at 09:00
  • 2
    The 31st of the month is not guaranteed to exist. But the 1st of each month is. So reverse the order of operations to ensure you have a valid date at each stage: `lubridate::floor_date(as.Date(end_date), "month") - months(1)`, as suggested by @Waldi. – Limey Jan 19 '22 at 09:03

1 Answers1

2

You could substract the month after floor:

end_date <- '2021-10-31'
floor_date(as.Date(end_date), 'month') - months(1)

[1] "2021-09-01"
ah bon
  • 9,293
  • 12
  • 65
  • 148
Waldi
  • 39,242
  • 6
  • 30
  • 78