【问题标题】:End of the (next) month from a random date从随机日期开始的(下)月末
【发布时间】:2020-06-04 10:51:39
【问题描述】:

我有一个问题,从一天中获得月末的最快方法是什么。我有一张非常大的桌子,我希望我的代码很快。我当前的代码如下所示:

library(lubridate)

end_of_month <- function(date){
 day(date) <- days_in_month(date)
 date
}

我还有一个问题。从随机日期获取下个月的最后一天是一种快速的方法吗?

"2019-05-15" %>% as.Date() %m+% months(1) %>% end_of_month  # 2019-06-30

我可以一步完成,还是需要一个额外的函数来处理这个?

【问题讨论】:

    标签: r date dplyr lubridate


    【解决方案1】:

    更新答案

    感谢@Edward 指出原始答案中的问题。

    原日期加1个月后即可使用ceiling_date

    ceiling_date(as.Date('2019-05-15') + months(1), unit = "month") - 1
    #[1] "2019-06-30"
    
    ceiling_date(as.Date('2019-04-15') + months(1), unit = "month") - 1
    #[1] "2019-05-31"
    

    旧答案

    我们可以使用ceiling_dateunit 作为'2 months'

    library(lubridate)
    '2019-05-15' %>% as.Date() %>% ceiling_date(unit = '2 months') - 1
    #[1] "2019-06-30"
    

    【讨论】:

    • @Edward 我没有测试过,但应该可以。还应考虑闰年。
    • 好的。只是您的代码(以及 OP)提前 1 个月返回偶数月,但提前 2 个月返回奇数月。所以我在挠头。
    • @Edward 你是对的。最初的答案没有按预期工作。我已经更新了答案。感谢您指出这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多