-1

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.

camille
  • 16,432
  • 18
  • 38
  • 60
  • It's hard to know exactly what's going on without a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Maybe you can post a sample of the strings that have this issue. I'm not sure why you're passing `d1` to `date`, when `mdy_hms` should have returned a datetime object already – camille May 15 '19 at 20:03
  • yeah...actually was just trying to do something with the value and forgot to make change in the code... – Pooja Gangurde May 16 '19 at 09:08

1 Answers1

1

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")

amrrs
  • 6,215
  • 2
  • 18
  • 27
  • 2
    I just want to inform you that ``as.Date(strptime("Feb 21, 2019 6:10 AM", "%b %d, %Y %H:%M %p"))`` returns NA on my R. – Gainz May 15 '19 at 19:59
  • 1
    @Gainz Maybe it's a locale issue. Check `Sys.getlocale('LC_TIME')` to see if you are running R with an English language date/time locale. – Rui Barradas May 15 '19 at 20:02
  • @RuiBarradas Yes I guess it is probably because of strptime() abbreviation using current locale. I was just wondering, thanks. Edit : Saw you edit, yes my R is not in the same locale, I wasn't sure strptime() was using the locale info tho. – Gainz May 15 '19 at 20:05
  • Mine is `"en_US.UTF-8"` and the result is proper. – amrrs May 15 '19 at 20:07
  • @Gainz `old_loc <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "en_US.UTF-8"); ; Sys.setlocale("LC_TIME", old_loc)`. – Rui Barradas May 15 '19 at 20:07
  • @RuiBarradas Yes thank you. I actually don't want to change it at the moment since I'm currently not using english dates. Altough, I appreciate your answer. – Gainz May 15 '19 at 20:09