2

I am trying to convert a character field into a date field for which the options are to either use strptime function or as.Date function. Here is two reproducible examples:

strptime(c("5/13/2015"),"%m/%d/%y")
#result is  "2020-05-13 MST"

as.Date(c("5/13/2015"), format = "%m/%d/%y")
#result is "2020-05-13"

Why did the functions change the year from 2015 to 2020? If instead, I format my date string and use the as.Date function it works. Here is what I did:

as.Date(c("2015/5/13"))

and it works fine.

any thoughts?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
seakyourpeak
  • 531
  • 1
  • 6
  • 18
  • 1
    As an aside note that you don't need `c(...)` as `c("5/13/2015")` is identical to `"5/13/2015"`. Also since these are dates with no times it is better to use `Date` class. – G. Grothendieck Nov 23 '19 at 15:19
  • 4
    Two digit years format is `"%y"`, **four** digits years is `"%Y"`. Upper case. – Rui Barradas Nov 23 '19 at 17:50

2 Answers2

6

Your date format string should use a capital "Y", which captures the full date with century, such as "2015". Lowercase "y" is used to capture the year in two digits, as when "2015" is written in shorthand as "15". In your original cases, the strptime and as.Date functions incorrectly interpret the "20" in "2015" as the 2-digit year. The corrected version:

strptime(c("5/13/2015"),"%m/%d/%Y")

"2015-05-13 EDT"
jdobres
  • 11,339
  • 1
  • 17
  • 37
2

I would highly recommend lubridate for date conversions

library(lubridate)

mdy("5/13/2015")

# [1] "2015-05-13"
stevec
  • 41,291
  • 27
  • 223
  • 311