How to correct date format?

I have a date column with different format.


Currently the class is factor and changed to date.

I want to convert all the date values to Day-Month-Year format.

When above date is printed values with 5/3/1992 or / values are shown as NA.

Welcome to the community!

In case you know the possible formats, it's possible in the first 2 of the following ways. If you don't, 3rd may work. But i'm not sure whether it'll work always or not.

# sample data
x <- c("1992-04-30", "5/3/1992", "1992-04-30", "4/30/1992")
y <- c("%Y-%m-%d", "%m/%d/%Y")

# base R
as.Date(x, y)
#> [1] "1992-04-30" "1992-05-03" "1992-04-30" "1992-04-30"

# tidyverse
lubridate::as_date(x, format=y)
#> [1] "1992-04-30" "1992-05-03" "1992-04-30" "1992-04-30"

# special package
#> [1] "1992-04-30" "1992-05-03" "1992-04-30" "1992-04-30"

Created on 2020-10-01 by the reprex package (v0.3.0)

Hope this helps.

1 Like

@Yarnabrina Thanks you, it works for all type of date format.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.