如何在 lubridate 中表示当月的第 15 天

how to express the 15th day of the current month in lubridate

我想创建一个 if-else 语句,如果当前日期在每月 15 号之后,它打印今天的日期,否则如果当前日期在 15 号之前,它应该打印上个月的日期每个月。我无法弄清楚如何在我的测试表达式的右侧表达当月的 15 日,关于如何做到这一点有什么想法吗?

library(lubridate)
ifelse(Sys.Date() >  15TH_OF_THE_MONTH, Sys.Date(), Sys.Date() - months(1))
library(lubridate)
ifelse(day(Sys.Date()) > 15, TRUE, FALSE)
[1] TRUE

我们可以做到

as.numeric(format(Sys.Date(), "%d")) > 15
[1] TRUE

为了避免大量强制转换(日期、数字、整数),我们可能希望使用 as.POSIXlt 允许以整数形式访问时间元素。

today <- as.POSIXlt(Sys.Date())
if (today$mday > 15L) today else {today$mon <- today$mon - 1L; today} 
# [1] "2021-09-30 UTC"

today <- as.POSIXlt("2021-09-14", tz='UTC')
if (today$mday > 15L) today else {today$mon <- today$mon - 1L; today} 
# [1] "2021-08-14 UTC"

或者,如果您想坚持 lubridate

library(lubridate)
today <- Sys.Date()
if (day(today) > 15L) today else {month(today) <- month(today) - 1L; today} 
# [1] "2021-09-30"

today <- as.Date("2021-09-14")
if (day(today) > 15L) today else {month(today) <- month(today) - 1L; today} 
# [1] "2021-08-14"

实际上,这就是 lubridate 正在做的事情。

lubridate:::mday.default
# function (x) 
# as.POSIXlt(x, tz = tz(x))$mday