rtimedate

Extract previous month from current date using timeDate library


I'm using the timeDate library instead of lubridate because it appears easier to determine when certain stock markets are open.

Given the current date, how do I extract the previous month in numeric form?

So if the current date is: "2022-12-09

prev_month = 11

And if the current date is: "2023-01-03"

prev_month = 12

library("timeDate")
current_date <- as.timeDate(Sys.Date())

Solution

  • library(timeDate)
    if (match(months(dt), month.name) == 1) 12  else  match(months(dt), month.name) - 1
    

    month.name is an object in base R containing the full month names. By using match, you can convert between the month names and month numbers.

    As months cycle from 1 to 12, when you step back from 1, you need to go to 12, not 0, hence the if statement for this special case.