Search code examples
rxts

Convert range of dates in narrative form to .xts dates


I have a character string "April 20, 2020 - April 24, 2020" and would like to convert it to two separate strings. There are two problems here: (1) recognizing that the narrative "April" is the 4th month, and (2) that there are two different dates in this string.

I have looked at the following, plus others, but don't see my answer:

[extract dates from date range][1],
[select a range of dates][2],
[convert dates to range][3]

I've also studied "parse" but that doesn't seem to be the answer.


Solution

  • Would something like this work ?

    string <- "April 20, 2020 - April 24, 2020"
    dates <- as.Date(strsplit(string, ' - ')[[1]], '%B %d, %Y')
    dates
    #[1] "2020-04-20" "2020-04-24"
    

    Or with lubridate::mdy if you don't want to remember the formats.

    dates <- lubridate::mdy(strsplit(string, ' - ')[[1]])
    

    Note that this is locale-dependent, your locale should be English.