0
0
R-programmingHow-ToBeginner · 3 min read

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 = ""): x is a date object.
  • format is a string with placeholders to define the output style.
  • Common placeholders include %Y for 4-digit year, %m for 2-digit month, %d for 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., %M for 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 CodeMeaningExample
%Y4-digit year2024
%y2-digit year24
%m2-digit month (01-12)06
%d2-digit day (01-31)15
%BFull month nameJune
%bAbbreviated month nameJun
%AFull weekday nameSaturday
%aAbbreviated weekday nameSat

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.