Search code examples
rseparatoras.dateformat-string

Trouble reformatting date with as.Date


I'm having a simple problem and I can't tell what's wrong. I'm trying to convert dates formatted "YYYY-MM-DD" to "m/d/YYYY". On my machine, this code:

x <- as.Date("2000-01-01")
x <- as.Date(x, format = "%m/%d/%Y")
print(x)

returns

"2000-01-01"

What am I missing?


Solution

  • as.Date() creates a date object where you tell it how to interpret the input with a format argument.

    format() (or alternatively strftime()) will convert a date object to a character object in a desired format:

    x <- as.Date("2000-01-01")
    x
    [1] "2000-01-01"
    
    str(x)
    Date[1:1], format: "2000-01-01"
    
    y <- format(x = x,format = "%m/%d/%Y")
    y
    [1] "01/01/2000"
    
    str(y)
    chr "01/01/2000"
    
    y <- strftime(x = x,format = "%m/%d/%Y")
    y
    [1] "01/01/2000"
    
    str(y)
    chr "01/01/2000"