How to Format Date in R: Simple Guide with Examples
In R, you can format dates using the
format() function by specifying a date object and a format string with placeholders like %Y for year, %m for month, and %d for day. This converts the date into a readable string in the format you want.Syntax
The basic syntax to format a date in R is:
format(x, format = ""):xis a date object.formatis a string with placeholders to define the output style.- Common placeholders include
%Yfor 4-digit year,%mfor 2-digit month,%dfor 2-digit day.
r
format(x, format = "%Y-%m-%d")Example
This example shows how to format the current date into different readable forms using format().
r
today <- Sys.Date() # Format as Year-Month-Day format(today, "%Y-%m-%d") # Format as Day/Month/Year format(today, "%d/%m/%Y") # Format as Month name Day, Year format(today, "%B %d, %Y")
Output
[1] "2024-06-15"
[1] "15/06/2024"
[1] "June 15, 2024"
Common Pitfalls
Common mistakes include:
- Trying to format a string instead of a date object.
- Using incorrect format codes (e.g.,
%Mfor month instead of%m). - Not converting character dates to Date class before formatting.
Always ensure your date is of class Date or POSIXct before formatting.
r
wrong_date <- "2024-06-15" # Wrong: formatting a string format(wrong_date, "%d/%m/%Y") # returns input unchanged # Right: convert to Date first correct_date <- as.Date(wrong_date) format(correct_date, "%d/%m/%Y")
Output
[1] "2024-06-15"
[1] "15/06/2024"
Quick Reference
| Format Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2024 |
| %y | 2-digit year | 24 |
| %m | 2-digit month (01-12) | 06 |
| %d | 2-digit day (01-31) | 15 |
| %B | Full month name | June |
| %b | Abbreviated month name | Jun |
| %A | Full weekday name | Saturday |
| %a | Abbreviated weekday name | Sat |
Key Takeaways
Use the format() function with a Date object to format dates in R.
Always convert strings to Date class before formatting to avoid errors.
Use correct format codes like %Y for year, %m for month, and %d for day.
Common mistake is confusing %M (minutes) with %m (month).
Refer to the quick reference table for common date format codes.