Offset a date by one month in R

Viewed 289

I have a date, let's say July 7th, 2020.

my_date <- as.Date("2020/07/07")

I want to offset this date by one month. So it should return August 7th, 2020.

I tried my_date + 30 but it doesn't work if the month has 30 or 31 days.

EDIT

I have to be precise in my question. What if the date is May 31, 2020? It should offset to June 30, 2020. Please, a help in base R is desirable.

Any help will be greatly appreciated.

2 Answers

Use %m+% from lubridate

library(lubridate)
my_date <- as.Date("2020/07/07")
my_date %m+% months(1)
#[1] "2020-08-07"

my_date + months(1) also works in this case but it messes up calculation if it's last day of month.

my_date <- as.Date("2020/05/31")
my_date + months(1)
#[1] NA

my_date %m+% months(1)
#[1] "2020-06-30"

You can use seq

> my_date <- as.Date("2020/07/07")
> seq(my_date,length=2,by="months")[2]
[1] "2020-08-07"
Related