Oli
Oli

Reputation: 542

Getting NA when using as.Date()

Thanks to comments below, I realized I should use "%b" for "FEB" (originally I used "%m"; thanks for the reference to ?strptime). But my problem still stands.

When I do

as.Date("13-FEB-15", "%d-%b-%y")
# [1] NA

I know this will work:

as.Date("13-02-2015", "%d-%m-%Y")
# [1] "2015-02-13"

But is there a way to avoid converting FEB to 02 and 15 to 2015 in order to get my expected result? Thanks!

Upvotes: 0

Views: 100

Answers (2)

Zheyuan Li
Zheyuan Li

Reputation: 73405

A general and useful diagnostic

Try this and what do you get?

format(strptime(Sys.Date(), format="%Y-%m-%d"), "%y-%b-%d")

I got

[1] "16- 7月-22"

Haha, the middle one is Chinese. So what is going wrong? Nothing wrong. The issue is that %b is sensitive to your current locale. When you read ?strptime, pay special attention to what format is sensitive to your current locale.

My locale is:

Sys.getlocale("LC_TIME")
#[1] "zh_CN.UTF-8"

Yep, that is in China region.

Locales make a difference in Date-Time format. On my machine:

as.Date("16-JUL-22", "%y-%b-%d")
# NA
as.Date("16- 7月-22", "%y-%b-%d")
#[1] "2016-07-22"

Now let's reset time locale:

Sys.setlocale("LC_TIME", "C")
as.Date("16-JUL-22", "%y-%b-%d")
#[1] "2016-07-22"

Wow, it works! Read ?locales for more, and you will understand what locale = "C" means.


Solution for you

Sys.setlocale("LC_TIME", "C")
as.Date("13-FEB-15", format = "%d-%b-%y")

Upvotes: 2

Boudewijn Aasman
Boudewijn Aasman

Reputation: 1256

Using lubridate:

library(lubridate)
date1 = "2014-12-11 00:00:00"
date2 = "14-DEC-11"
ymd_hms(date1) == ymd(date2,tz = "UTC")

These equal each other and should be able to be joined.

Upvotes: 2

Related Questions