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