R Language Date and Time Move a date a number of months consistently by months


Example

Let's say we want to move a given date a numof months. We can define the following function, that uses the mondate package:

moveNumOfMonths <- function(date, num) {
    as.Date(mondate(date) + num)
}

It moves consistently the month part of the date and adjusting the day, in case the date refers to the last day of the month.

For example:

Back one month:

> moveNumOfMonths("2017-10-30",-1)
[1] "2017-09-30"

Back two months:

> moveNumOfMonths("2017-10-30",-2)
[1] "2017-08-30"

Forward two months:

> moveNumOfMonths("2017-02-28", 2)
[1] "2017-04-30"

It moves two months from the last day of February, therefore the last day of April.

Let's se how it works for backward and forward operations when it is the last day of the month:

> moveNumOfMonths("2016-11-30", 2)
[1] "2017-01-31"
> moveNumOfMonths("2017-01-31", -2)
[1] "2016-11-30"

Because November has 30 days, we get the same date in the backward operation, but:

> moveNumOfMonths("2017-01-30", -2)
[1] "2016-11-30"
> moveNumOfMonths("2016-11-30", 2)
[1] "2017-01-31"

Because January has 31 days, then moving two months from last day of November will get the last day of January.