1

I'm trying to convert this 2008-01-01 to 1/1/2008 in R. I've tried as.Date(abc,'%m/%d/%y') but it doesn't work...instead I get a bunch of NAs.

Any ideas?

Kashif
  • 3,063
  • 6
  • 29
  • 45
  • Downvote for no research effort. Pasting your exact question title into the 'ask question' title box lists the duplicate under 'questions that may already have your answer' – thelatemail Aug 04 '15 at 00:38
  • My question was a little different actually...and these solutions are also much quicker than those listed previously. I searched for an hour on this. – Kashif Aug 04 '15 at 00:56
  • You searched for an hour? The first page of Google results for 'R change date format' gives the same answers as below, along with several other R-bloggers articles and tutorials covering this material. Even searching for your exact question title on Google gives several positive results with the same info. – thelatemail Aug 04 '15 at 01:21
  • Yeah, I tried those other methods as well. They didn't use the 'gsub' method at least. I saw `as.Date(d,'%m/%d/%y')` which still didn't give me the result I wanted. In fact, I was getting these values like "0001-01-20" "0001-02-20" "0001-03-20" "0001-04-20" "0001-05-20" which didn't make any sense. – Kashif Aug 04 '15 at 01:30
  • `Browse[2]> head(dates1) [1] "0001-01-20" "0001-02-20" "0001-03-20" "0001-04-20" "0001-05-20" "0001-06-20"` `Browse[2]> okay1 <- as.Date(dates1, format="%m/%d/%y")` `Browse[2]> head(okay1) [1] "0001-01-20" "0001-02-20" "0001-03-20" [4] "0001-04-20" "0001-05-20" "0001-06-20"` So even with googling I was still getting something strange. – Kashif Aug 04 '15 at 01:33

2 Answers2

8

I'm assuming that 2008-01-01 is a string, and that you want 1/1/2008 to also be a string.

You can do this using format(), but there's likely a better solution. And if you really want no zeros in your output (as opposed to 01/01/2008) then I do not think format() will help you.

Date = "2008-01-01" 
format(as.Date(Date, '%Y-%m-%d'), "%m/%d/%Y")
Jared Smith
  • 280
  • 3
  • 12
2

Since your input date is in ISO 8601 format, you can call as.Date() on it directly to get a Date-classed object, and then format() can be used to stringify it in any format specifiable using the format specifiers documented here.

d <- '2008-01-01';
format(as.Date(d),'%m/%d/%Y');
## [1] "01/01/2008"

If you really don't want those leading zeroes, you'll have to strip them off yourself using gsub():

gsub('\\b0+','',format(as.Date(d),'%m/%d/%Y'));
## [1] "1/1/2008"
bgoldst
  • 34,190
  • 6
  • 38
  • 64