The following table shows a variety of symbols that you can use to format dates in R:
| Symbol | Definition | Example |
|---|---|---|
| %d | Day as a number | 19 |
| %a | Abbreviated weekday | Sun |
| %A | Unabbreviated weekday | Sunday |
| %m | Month as a number | 04 |
| %b | Abbreviated month | Feb |
| %B | Unabbreviated month | February |
| %y | 2-digit year | 14 |
| %Y | 4-digit year | 2014 |
The following examples show how to use each of these formats in practice.
Example 1: Format Date with Day, Month, Year
The following code shows how to format a date using a month/day/year format:
#define date date <- as.Date("2021-01-25") #format date formatted_date <- format(date, format="%m/%d/%y") #display formatted date formatted_date [1] "01/25/21"
Note that we can use whatever separators we’d like in between each value.
For example, we could use dashes instead:
#define date date <- as.Date("2021-01-25") #format date formatted_date <- format(date, format="%m-%d-%y") #display formatted date formatted_date [1] "01-25-21"
Example 2: Format Date as Weekday
The following code shows how to format a date using a weekday format:
#define date date <- as.Date("2021-01-25") #format date as abbreviated weekday format(date, format="%a") [1] "Mon" #format date as unabbreviated weekday format(date, format="%A") [1] "Monday"
Example 3: Format Date as Month
The following code shows how to format a date as a month:
#define date date <- as.Date("2021-01-25") #format date as abbreviated month format(date, format="%b") [1] "Jan" #format date as unabbreviated month format(date, format="%B") [1] "January"
We can also format the date as a month and a day:
#define date date <- as.Date("2021-01-25") #format date as abbreviated month format(date, format="%b %d") [1] "Jan 25"
Additional Resources
The following tutorials explain how to perform other common operations involving dates in R:
How to Sort a Data Frame by Date in R
How to Subset by a Date Range in R
How to Convert Strings to Dates in R
Hi my data dates are shown in the format below. Can you please advise why ? thank you.
> date formatted_date formatted_date
[1] “20/12/0015”
This should be titled a concise guide as it in incomplete
I notice all examples are dates of recent times. What about using dates such as 23 April 1564? Or 15 May 55 BCE (Before Common Era)?
How do we use R to handle those sorts of dates?