Add 6 months to a date starting february
我正在尝试使用 lubridate 库从 2 月到日期减去 3 个月,但是,它总是给我 28 的日期。我知道很多人都问过这个问题,但我尝试了很多东西,但是仍然是同样的错误。循环一天是一种选择。但是,我一直在寻找有效的东西
我的代码是这样的:
其中 test_end = "2019-02-28"
和 lastnmonth = 3
我总是得到输出为 "2018-11-28" 而不是 "2018-11-30"
使用 Dirk 的策略,我们可以设计一个函数来处理这种类型的操作:
1 2 3 4 5 6 7 8 9 10 11 12 | start_date <- lubridate::ymd("2019-02-28") mths_to_subtract <- 3 deduct_mth <- function(date_object = start_date, mths_to_deduct = mths_to_subtract){ days_to_ceiling_date <- lubridate::ceiling_date(date_object,"months") - date_object date_object + days_to_ceiling_date - lubridate::period(mths_to_deduct,"months") - days_to_ceiling_date } |
给出以下答案:
1 2 3 4 | > deduct_mth(ymd("2019-02-28"), 3) [1]"2018-11-30" > deduct_mth(ymd("2000-02-29"), 3) [1]"1999-11-30" |
你想要一个月的最后一天——所以你可以使用下一个是第一个的技巧,将它移动月数——然后减去一天。
在一行base R:
1 2 3 | R> seq(as.Date("2019-02-28") + 1, length=4, by="-1 month") - 1 [1]"2019-02-28""2019-01-31""2018-12-31""2018-11-30" R> |
我们添加一天,然后使用四个月的序列(包括当前)倒数,然后取出一天作为上个月的最后一天。
如果你只想要一个,只需添加
1 2 3 | R> tail(seq(as.Date("2019-02-28") + 1, length=4, by="-1 month") - 1, 1) [1]"2018-11-30" R> |
1 | lubridate::ymd("2019-02-28") - lubridate::period(3,"months") |
额外的代码来锻炼 mont-end
1 | lubridate::ceiling_date(lubridate::ymd("2019-02-28") - lubridate::period(3,"months"),"months") - lubridate::ddays(1) |