Home > Blockchain >  How to round the date to the first day of the month when subtracting dates in R
How to round the date to the first day of the month when subtracting dates in R

Time:01-04

I need to calculate the difference between the current month and the last. I do so

library(lubridate)
last_month <- Sys.Date() - months(1)

and the result

> last_month
[1] "2022-12-04"

This is the correct answer, but I need the received date to always be from the first day like this "2022-12-01".

That is, round it up to the first day of the month?

For example, when I do this in February,4 day , the result will be "2023-01-04", but i need that it would be "2023-01-01".

How to round the date to the first day of the month when subtracting dates like this? thanks for your help

CodePudding user response:

You can use format, i.e.

format(Sys.Date() - months(1), '%Y-%m-01')
#[1] "2022-12-01"

CodePudding user response:

You could use floor_date from lubridate based on month like this:

library(lubridate)
last_month <- Sys.Date() - months(1)
floor_date(last_month, "month")
#> [1] "2022-12-01"

Created on 2023-01-04 with reprex v2.0.2

  • Related