R:使用 lubridate 到月末的天数

R: number of days to month end using lubridate

我正在尝试使用 lubridate 包计算当月剩余的天数。我已经能够使用下面的代码成功完成此操作;但是,这似乎非常冗长且难以阅读。

as.duration(interval(start = ymd(Sys.Date()), end =  ceiling_date(Sys.Date(), unit = "month"))) / ddays(1)

有更简单的方法吗?

在 lubridate 中你可以做:

days_in_month(now()) - mday(now())

虽然这给了你一个命名向量,所以最好这样做

as.numeric(days_in_month(now()) - mday(now()))
#> [1] 27

感谢@H1 指出我们可以使用 now() 而不是 month(now())

根据@WaltS的建议,我们可以用ceiling_date以"month"为单位得到下个月的开始日期,减去1天得到当月的结束日期,然后减去今天的日期得到该月的剩余天数。

as.integer(ceiling_date(today(), "months") - today() - 1)