Display a character column to mm/dd/yyyy format

Hi all,
from the snap, I have a column LBSTDAT_RAW which has date values in DD-MMM-YY format and i need to convert in to a format MM/DD/YYYY format. eg: the value 21-Apr-22 should be displayed as 04/21/2022. i also have date, month, year values in 3 different columns as numeric variables, can we use those to get the desired results?

your help will be highly appreciated.

how to achieve this, please suggest?

date

The mm/dd/yyyy format is a borderline crime in my opinion, and should never be used, but if you insist:

x = as.Date("2022-04-21")
print(x)
print(format(x, "%m/%d/%Y"))

1 Like

I totally agree with mduvekot

A very slightly different approach is

library(lubridate)
dd = dmy(c("21-Apr-22", "17-Sep-22"))
dat = format(dd, "%m/%d/%Y")

This is assuming that the dates shown in your screenshot are character variables and the output is character.

In both @ mduvekot case and mine the output is character not a date.

Can you explain to us what you are doing here?

2 Likes

Adding on to the (correct) suggestions given here: on computers, when you turn dates into DateTime datatypes (which is always recommended so you can do analyses on them), they are always in the format YYYY-MM-DD. This is an international standard (ISO - ISO 8601 — Date and time format). Regardless of your operating system or programming language, that is the standard for DateTime datatypes. If this is what you are looking for, you should use the package lubridate: it has functions that you can apply to pretty much any of the columns that are showing in your example to turn the dates into "proper" DateTime datatypes.

However, if your question only relates to visualization purposes, e.g. you're making a table, or this particular column represents labels you want to add to a plot, then you have to make the dates character datatype, as suggested in the previous answers. But note that they then behave as characters, not DateTime, when it comes to things like ordering and other data manipulation.