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

Time:09-30

I would like to create an if-else statement, where it prints today's date if the current date is after the 15th of every month, or else it should print last month's date if the current date is before the 15th of every month. I'm having trouble figuring out how to express the 15th of the current month in the right hand side of my test expression, any ideas on how to do this?

library(lubridate)
ifelse(Sys.Date() >  15TH_OF_THE_MONTH, Sys.Date(), Sys.Date() - months(1))

CodePudding user response:

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

CodePudding user response:

We can just do

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

CodePudding user response:

In order to avoid extensive coercing (date, numeric, integer) we may want to use as.POSIXlt which allows to access time elements as integers.

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"

Or, if you want to stick with 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"

Actually, that's what lubridate is doing under the hood.

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