简体   繁体   English

从2月开始的日期增加6个月

[英]Add 6 months to a date starting february

I am trying to subtract 3 months from February to a date using lubridate library, however, it always gives me date as 28. I know a lot of people have asked this question, but I have tried a lot of things, but still the same error. 我正在尝试使用lubridate库从2月到日期减去3个月,但是,它始终将我的日期设为28。我知道很多人都问过这个问题,但是我尝试了很多事情,但仍然是一样的错误。 Looping through the day is an option. 循环一天是一种选择。 However, I was looking for something efficient 但是,我一直在寻找高效的东西

what my code does is this: 我的代码是这样的:

where test_end = "2019-02-28" and lastnmonth = 3 其中test_end =“ 2019-02-28”并且lastnmonth = 3

as.Date(test_end) %m-% months(lastnmonth)

I always get the output as "2018-11-28" instead of "2018-11-30" 我总是得到的输出是“ 2018-11-28”而不是“ 2018-11-30”

lubridate::ymd("2019-02-28") - lubridate::period(3, "months")

解决蒙特问题的附加代码

lubridate::ceiling_date(lubridate::ymd("2019-02-28") - lubridate::period(3, "months"), "months") - lubridate::ddays(1)

You want the last of the month -- so you can use the trick that the next is a first, move that one by the number of months -- and then substract one day. 您需要一个月的最后一个月-这样您就可以使用下一个是第一个的技巧,将其移动几个月,然后减去一天。

All in one line of base R: 全部位于基数R的一行中:

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> 

We add one day, then use a sequence of four months (including current) backwards, and take out one day to be on the last day of the previous month. 我们添加一天,然后使用四个月(包括当前)的顺序倒数,然后减去上个月最后一天的一天。

If you just want one, simply add tail(..., 1) : 如果只想要一个,只需添加tail(..., 1)

R> tail(seq(as.Date("2019-02-28") + 1, length=4, by="-1 month") - 1, 1)
[1] "2018-11-30"
R> 

Using Dirk's strategy we can draw-up a function to handle this type of operation: 使用Dirk的策略,我们可以草拟一个函数来处理这种类型的操作:

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

}

Gives the following answers: 给出以下答案:

> deduct_mth(ymd("2019-02-28"), 3)
[1] "2018-11-30"
> deduct_mth(ymd("2000-02-29"), 3)
[1] "1999-11-30"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM