Search code examples
rdater-faq

as.Date returning NA while converting from 'ddmmmyyyy'


I am trying to convert the string "2013-JAN-14" into a Date as follow :

sdate1 <- "2013-JAN-14"
ddate1 <- as.Date(sdate1,format="%Y-%b-%d")
ddate1

but I get :

[1] NA

What am I doing wrong ? should I install a package for this purpose (I tried installing chron) .


Solution

  • Works for me. The reasons it doesn't for you probably has to do with your system locale.

    ?as.Date has the following to say:

    ## This will give NA(s) in some locales; setting the C locale
    ## as in the commented lines will overcome this on most systems.
    ## lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
    x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
    z <- as.Date(x, "%d%b%Y")
    ## Sys.setlocale("LC_TIME", lct)
    

    Worth a try.