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 Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2024 |
| %y | 2-digit year | 24 |
| %m | 2-digit month | 06 |
| %d | 2-digit day | 15 |
| %H | 24-hour | 14 |
| %I | 12-hour | 02 |
| %M | Minutes | 30 |
| %S | Seconds | 00 |
| %p | AM/PM | PM |
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.