R How to convert date format

Viewed 881

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

3 Answers

You could use the anytime package:

library(anytime)
string <- '22APR2020'
anytime::anydate(string)
[1] "2020-04-22"

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).

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.

Related