Search code examples
rdatetime-conversion

Converting Feb 21, 2019 6:10 AM to mm/dd/yyyy in R


I am trying to convert my date from Feb 21, 2019 6:10 AM to mm/dd/yyyy format and have used lubridate::mdy_hms() like this:

d1=mdy_hms(data$`First Activity (America/New_York)`)
data$`First Activity (America/New_York)` <- date(d1)

Now this converts my date to mm/dd/yyyy format but the year is converted to 2020. I can't debug why is my year incrementing by 1.


Solution

  • you can use base-R function for this.

    as.Date(strptime("Feb 21, 2019 6:10 AM", "%b %d, %Y %H:%M %p"))
    #> [1] "2019-02-21"
    

    Created on 2019-05-16 by the reprex package (v0.2.1)

    For the exact output format that you required, you can wrap it with another format function

    format((strptime("Feb 21, 2019 6:10 AM", "%b %d, %Y %H:%M %p")),"%m/%d/%Y")