2

I was looking to convert the following character string in a date format:

string <- '22APR2020'
date <- as.Date(string, format='%d%b%y')
date
>>> NA

Unfortunately, the result is NA and I need to convert it as a date in order to being able to calculate the time between two dates.

Thanks you

John E.
  • 137
  • 2
  • 10
  • Seems like a locale issue. Check [strptime, as.POSIXct and as.Date return unexpected NA](https://stackoverflow.com/questions/13726894/strptime-as-posixct-and-as-date-return-unexpected-na) – Henrik Jun 16 '20 at 12:28

3 Answers3

3

You could use the anytime package:

library(anytime)
string <- '22APR2020'
anytime::anydate(string)
[1] "2020-04-22"
Ahorn
  • 3,686
  • 1
  • 10
  • 17
  • I am not sure which one between anytime and lubridate package is the most maintained over time. Right now, your answer is valid. Which one would you recommend? – John E. Jun 16 '20 at 13:17
1

The problem is your locale setting. It probably is set to a language where the fourth month is not abbreviated as "APR".

Sys.setlocale("LC_TIME", "French")

string <- '22APR2020'
as.Date(string, format='%d%b%Y')
#[1] NA

Sys.setlocale("LC_TIME", "German")
as.Date(string, format='%d%b%Y')
#[1] "2020-04-22"

Also, note the capital Y is used in the format string. It's important. y only refers to the decade (it would give the same result, by chance, for 2020, but give the wrong result for 2021).

Roland
  • 127,288
  • 10
  • 191
  • 288
1

When in doubt always use lubridate:

string <- '22APR2020'
library(lubridate)
dmy(string)
[1] "2020-04-22"

here dmy is order of date, month and year appearance.

Harshal Gajare
  • 605
  • 4
  • 16