John E.
John E.

Reputation: 137

R How to convert date format

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

Upvotes: 2

Views: 1667

Answers (3)

Harshal Gajare
Harshal Gajare

Reputation: 615

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.

Upvotes: 1

Roland
Roland

Reputation: 132969

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

Upvotes: 1

Ahorn
Ahorn

Reputation: 3876

You could use the anytime package:

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

Upvotes: 3

Related Questions