0

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.

W Barker
  • 324
  • 2
  • 8
  • May be you can split and convert both strings to date. For recognising two dates in string you can search that string. – AnilGoyal Oct 12 '20 at 14:00

2 Answers2

1

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Yes, this works. Thanks. I wasn't aware of "strsplit", but I have a couple of questions: I recognize the hyphen in the single quote marks, but I don't see in the description of "strsplit" what is being called for here. Also, I need help in interpreting the double brackets with the 1. – W Barker Oct 12 '20 at 15:59
  • That is the `split` part in `strsplit` meaning on which pattern do we expect to split our string. `strsplit` returns a list so using `[[1]]` we make it a vector. This is same as using `unlist` i.e `unlist(strsplit(string, ' - '))` – Ronak Shah Oct 12 '20 at 22:38
  • 1
    Coffee's on me! – W Barker Oct 13 '20 at 14:43
0

We can use anydate

library(anytime)
anydate(strsplit(string, "\\s*-\\s*")[[1]])
#[1] "2020-04-20" "2020-04-24"
akrun
  • 874,273
  • 37
  • 540
  • 662