Search code examples
rformatposixctdate-conversion

R date conversion


I have a date in format "%e-%a-%y" example: "13-Mar-15"

I need to convert this date in format "%Y-%m-%d"

I have tried format(example, "%Y-%m-%d") without success. Also tried

format(as.POSIXct(example, format="%e-%a-%y"), format="%Y-%m-%d")

without success.

Edit: I know what happened I had the wrong format:"%e-%a-%y".
It needed to be "%d-%b-%y" It was late and when I wrote my initial format, so I wasn't thinking very clearly: "%a" was for the abbreviated day.
The error was that I was trying to convert without the proper source format. "%b" is the abbreviated month, which should work for this question.


Solution

  • You had the wrong format :

    as.Date("13-Mar-15", "%d-%b-%y")
    [1] "2015-03-13"
    

    For the formats, %d is the day, %b is the abbreviated month and %y the year (two-digits)

    %a is an abbreviated weekday name. You could also use

    as.Date("13-Mar-15", "%e-%b-%y")
    [1] "2015-03-13"
    

    as %e is also the day (format 1-31) where %d is 01-31. read ?strptime for more info on the date format.