1

I have my string formatted as: 20170814 and wanted to convert to date by as.Date function but keep producing me 'NA". This is my function:

a<-"20170814"
as.Date(a,"%y-%m/%d")

Can you please give me some help Thanks

hn.phuong
  • 835
  • 6
  • 15
  • 24
  • 1
    `as.Date(a,"%Y%m%d")` – akrun Mar 05 '18 at 23:16
  • 1
    You don't have dashes or slashes in your date, so don't include them in your `format` string. – Gregor Thomas Mar 05 '18 at 23:16
  • 2
    Looks like this has been answered several time, two possible dupes: https://stackoverflow.com/questions/14755425/what-are-the-standard-unambiguous-date-formats ; https://stackoverflow.com/questions/20061469/cannot-convert-string-to-date-in-r – Mike H. Mar 05 '18 at 23:22

3 Answers3

2

The format is %Y%m%d and there is no -

as.Date(a,"%Y%m%d")
#[1] "2017-08-14"

Another option is anytime which can parse most of the formats and convert it to Date class

anytime::anydate(a)
#[1] "2017-08-14"

class(anytime::anydate(a))
#[1] "Date"
akrun
  • 874,273
  • 37
  • 540
  • 662
2

One solution with lubridate:

lubridate::ymd(a)

# [1] "2017-08-14"

class(lubridate::ymd(a))

# [1] "Date"
tyluRp
  • 4,678
  • 2
  • 17
  • 36
1

You want to use

as.Date(a, "%Y%m%d")
# [1] "2017-08-14"

because "%Y%m%d" is the description of the format of the character that you provide, which does not include / or -. Also, Y is needed when the year consists of 4 digits rather than 2.

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102