1

How to convert a string such as 20100502 into date format %m/%d/%Y

I tried to convert using

as.Date(20100502, origin="1970-01-01", format = "%Y-%m-%d") 

But, the result is "57003-04-23" instead of 05/02/2010

1
  • 1
    You need to convert the string to a Date object and then back to a string with a different format. In the first step you have to specify the format of the input string (not the one you want eventually): x<-as.Date("20100502", format = "%Y%m%d"). Then with format you specify the output format: format(x,format="%m/%d/%Y"). Commented Oct 8, 2018 at 13:06

2 Answers 2

4

You can use as.Date and format

format(as.Date("20100502", format = "%Y%m%d"), "%m/%d/%Y") #[1] "05/02/2010" 

The format argument in as.Date refers to the format in which you provide your data to the function. Then in the function format you provide the format that you desire.


from ?as.Date

as.Date will accept numeric data (the number of days since an epoch), but only if origin is supplied.

A workaround as suggested by @Wimpel in comments is to wrap x in as.character.

X$new_Date <- format(as.Date(as.character(X$Date), format = "%Y%m%d"), "%m/%d/%Y") 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I tried the code to call X$Date from my .csv file that has multiple dates. But, I am getting an error 'origin' must be supplied. When I supply with origin = lubridate::origin, I am getting the result as "04-24-57003".
@GN Can you add the output of dput(head(X$Date)) at the end of your question?
@GN X$Date has to be character-format. If not, make it so using as.character().
Sure, it's c(20100502L, 20100502L, 20100502L, 20100502L, 20100502L, 20100502L
0

If you already know regular expressions then that provides a very generalisable way of manipulating string variables:

date <- "20100502" gsub("(\\d{4})(\\d{2})(\\d{2})", "\\2/\\3/\\1", date) #[1] "05/02/2010" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.