Dynamic date object issues

I've got a problem when creating some dynamic date objects.

library(lubridate)
day <- as.Date(Sys.time())
this_m <- format(day,"%m")
next_m <- format(day + months(1), "%m")
m_after <- format(day + months(2), "%m")

For some reason the next_m object delivers an object that is considered 'chr NA' while the m_after object delivers the correct value (as of today, a character object of "03"). Previously the next_m object has delivered the intended result, however today it's giving the result described above. This is very strange given that m_after works fine. Does anyone know how I can fix this? Any help is greatly appreciated.

I need create an object that has the numeric version of the month in two digits, e.g March is 03 rather than just 3

Hi there,

According to the documentation, you should use the special operator %m+% to add days/months/years to a date object. It will also correct for impossible dates. So to update your code simply do this:

library(lubridate)

day <- as.Date(Sys.time())
this_m <- format(day,"%m")
next_m <- format(day %m+% months(1), "%m")
m_after <- format(day %m+% months(2), "%m")

m_after
#> [1] "03"
next_m
#> [1] "02"

Created on 2023-01-30 with reprex v2.0.2
Hope this helps,
PJ

2 Likes

That is a character string. If you need it to be a character string representation of a portion of a Date object, which is typeof double while still keeping the object intact, it may take some doing.

On the other hand if you just need typeof character,

get_mons <- function(x = NULL) {
  start = lubridate::month(Sys.Date())
  char_mons = c("01","02","03","04","05","06",
                 "07","08","09","10","11","12")
  char_mons[start + x]
}

(this_month <- get_mons(0))
#> [1] "01"
(next_month <- get_mons(1))
#> [1] "02"
(month_after <- get_mons(2))
#> [1] "03"

But you'd have to address year-end wrap-around going more months out.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.