Add/subtract 6 months (bond time) in R using lubridate

前端 未结 2 1338
野的像风
野的像风 2020-12-05 00:43

I am looking to add and subtract six months reliably with lubridate.

For example, adding six months to 12/31/2014 should result in 6

2条回答
  •  粉色の甜心
    2020-12-05 01:22

    The lubridate function %m+% may be useful here:

    Add and subtract months to a date without exceeding the last day of the new month

    as.Date("2014-12-31") %m+% months(6)
    # [1] "2015-06-30"
    

    To also handle the second case, you will need to round up to nearest month using ceiling_date, and subtract one day using days.

    ceiling_date(as.Date("2014-02-28") %m+% months(6), unit = "month") - days(1)
    # [1] "2014-08-31"
    

提交回复
热议问题