Here are two ways to convert Date to Character in R:
- Using as.character()
- Using format()
Method 1: Using as.character()
dates <- c("11/20/80", "11/20/91", "11/20/1993", "09/10/93")
dt <- as.Date(dates, "%m/%d/%y")
strDates <- as.character(dt)
strDates
Output
[1] "1980-11-20" "1991-11-20" "2019-11-20" "1993-09-10"
Method 2: Using format()
If you need to format the date in a specific way during the conversion, you can use the format() function
today <- Sys.Date()
format(Sys.Date(), format = "%d %B, %Y")
format(Sys.Date(), format = "Today is a %A!")
Output
[1] "24 May, 2023"
[1] "Today is a Wednesday!"
You can see that we get the date in the character format.
When using format(), it’s essential to specify the desired format correctly.
The formatting strings like %Y for year, %m for month, and %d for day are standard.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.