Get startedGet started for free

Date formats (2)

Not only can you convert characters to dates, but you can convert objects that are already dates to differently formatted dates using format():

# The best point move in stock market history. A +936 point change in the Dow!
best_date
[1] "2008-10-13"

format(best_date, format = "%Y/%m/%d")
[1] "2008/10/13"

format(best_date, format = "%B %d, %Y")
[1] "October 13, 2008"

As a reminder, here are the formats:

  • %Y: 4-digit year (1982)
  • %y: 2-digit year (82)
  • %m: 2-digit month (01)
  • %d: 2-digit day of the month (13)
  • %A: weekday (Wednesday)
  • %a: abbreviated weekday (Wed)
  • %B: month (January)
  • %b: abbreviated month (Jan)

This exercise is part of the course

Intermediate R for Finance

View Course

Exercise instructions

  • Create the vector dates from char_date, specifying the format so R reads them correctly.
  • Modify dates using format() so that each date looks like "Jan 04, 17".
  • Modify dates using format() so that each date looks like "01,04,2017".

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

char_dates <- c("1jan17", "2jan17", "3jan17", "4jan17", "5jan17")

# Create dates using as.Date() and the correct format 
dates <- ___

# Use format() to go from "2017-01-04" -> "Jan 04, 17"
___

# Use format() to go from "2017-01-04" -> "01,04,2017"
___
Edit and Run Code