I am trying to convert "March 15, 2017"
to date.
as.Date("March 15, 2017", "%B %d, %Y")
and it returned NA
I feel that the syntax fits well, what is the problem?
Asked
Active
Viewed 103 times
1

Roman Luštrik
- 69,533
- 24
- 154
- 197

B.LIANG
- 69
- 1
- 5
-
If I copy the example in the documentation, it still don't work on my machine. Is there something wrong? – B.LIANG Jan 20 '18 at 06:54
-
But if i run this in the documentation console, it worked... – B.LIANG Jan 20 '18 at 06:54
-
It is really weird. – B.LIANG Jan 20 '18 at 07:00
-
this seems to be a local issue, I cannot replicate it. what is your version of **R** and what OS are you using? – Dror Bogin Jan 20 '18 at 07:32
-
1@DrorBogin it's a locale thing and indeed a "local" issue. – Roman Luštrik Jan 20 '18 at 07:50
1 Answers
2
You are close, but have been bitten by your locale. If you look at the documentation for strptime
, you will notice that
%B Full month name in the current locale. (Also matches abbreviated name on input.)
This is also the case for my system since Slovenian doesn't have English month names:
> as.Date("March 15, 2017", "%B %d, %Y")
[1] NA
> Sys.getlocale()
[1] "LC_COLLATE=Slovenian_Slovenia.1250;LC_CTYPE=Slovenian_Slovenia.1250;LC_MONETARY=Slovenian_Slovenia.1250;LC_NUMERIC=C;LC_TIME=Slovenian_Slovenia.1250"
What you can do is change locale, perhaps only for the duration of the conversion.
> Sys.setlocale(locale = "English")
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
> as.Date("March 15, 2017", "%B %d, %Y")
[1] "2017-03-15"
And then back to normal
> Sys.setlocale(locale = "Slovenian")
[1] "LC_COLLATE=Slovenian_Slovenia.1250;LC_CTYPE=Slovenian_Slovenia.1250;LC_MONETARY=Slovenian_Slovenia.1250;LC_NUMERIC=C;LC_TIME=Slovenian_Slovenia.1250"
> as.Date("March 15, 2017", "%B %d, %Y")
[1] NA
But if I use a Slovenian name for March:
> as.Date("Marec 15, 2017", "%B %d, %Y")
[1] "2017-03-15"
Locale name will depend on your operating system, see ?Sys.setlocale
for more info.

Roman Luštrik
- 69,533
- 24
- 154
- 197