0
0
RubyHow-ToBeginner · 3 min read

How to Format Date in Ruby: Simple Guide with Examples

In Ruby, you format dates using the strftime method on Date or Time objects. You provide a format string with placeholders like %Y for year or %m for month to get the date in your desired style.
📐

Syntax

The strftime method formats a date or time object into a string based on the format you specify. The format string uses percent signs followed by letters to represent parts of the date.

  • %Y: 4-digit year (e.g., 2024)
  • %m: 2-digit month (01-12)
  • %d: 2-digit day of the month (01-31)
  • %H: 24-hour (00-23)
  • %M: minutes (00-59)
  • %S: seconds (00-59)
ruby
date.strftime("%Y-%m-%d")
💻

Example

This example shows how to get the current date and time, then format it as a string like "2024-06-15 14:30:00".

ruby
require 'date'

now = DateTime.now
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
puts formatted
Output
2024-06-15 14:30:00
⚠️

Common Pitfalls

One common mistake is using the wrong format codes or forgetting that strftime returns a string and does not change the original date object. Also, mixing up Date and Time objects can cause confusion because Date does not have time information.

ruby
require 'date'

# Wrong: Using Date object but expecting time
my_date = Date.today
puts my_date.strftime("%Y-%m-%d %H:%M:%S") # %H, %M, %S will show 00:00:00

# Right: Use DateTime or Time for time info
my_time = DateTime.now
puts my_time.strftime("%Y-%m-%d %H:%M:%S")
Output
2024-06-15 00:00:00 2024-06-15 14:30:00
📊

Quick Reference

Format CodeMeaningExample
%Y4-digit year2024
%y2-digit year24
%m2-digit month06
%d2-digit day15
%H24-hour14
%I12-hour02
%MMinutes30
%SSeconds00
%pAM/PMPM

Key Takeaways

Use the strftime method on Date or Time objects to format dates in Ruby.
Format strings use percent codes like %Y for year and %m for month.
Date objects do not include time; use DateTime or Time for time formatting.
strftime returns a formatted string; it does not modify the original date object.
Check format codes carefully to avoid unexpected output.