Vaibhav Thakur
Vaibhav Thakur

Reputation: 119

How to convert dd/mm/yy to yyyy-mm-dd in R

I have a vector with dates values in this format dd/mm/yy e.g.(27/06/16). I want to convert this in this format yyyy-mm-dd e.g.(2016-06-27) for logical comparison. I am using this expression:

as.Date(as.character("27/06/16"), format = "%d")

and output comes out as:

"2016-07-27"

How can I convert this into required format.

Upvotes: 7

Views: 38496

Answers (6)

EricV
EricV

Reputation: 1

Using dplyr

df.with.converted.date <- df.with.original.date %>%
  mutate(new.date.var = as.character(as.Date(old.date.var, "%m/%d/%Y"),"%Y%m%d"))

For example this will convert "5/3/2019" to 20190503

Upvotes: 0

Al Ameen
Al Ameen

Reputation: 372

strDates <- c("27/06/16")
dates <- as.Date(strDates, "%m/%d/%Y")

this works.

refer this for more.http://www.statmethods.net/input/dates.html

Upvotes: -1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

One option would be to convert both date formats into a common POSIX representation:

d1 <- strptime("27/06/16", "%d/%m/%y")
d2 <- strptime("2016-06-27", "%Y-%m-%d")

Since both d1 and d2 should be of the same R class, you can then just compare them as you wish.

Upvotes: 3

WillardSolutions
WillardSolutions

Reputation: 2314

Try

as.Date( as.character("27/06/16"), format = "%Y-%m-%d")

Upvotes: -3

J_F
J_F

Reputation: 10352

With base R

as.Date(as.character("27/06/16"), format = "%d/%m/%y")

Upvotes: 4

user2100721
user2100721

Reputation: 3587

Use lubridate package

library(lubridate)
dmy("27/06/16")

Upvotes: 21

Related Questions