Reason #85 •
March 26th, 2026
Creating time strings with Time#strftime
The Time#strftime method allows us to create formatted time strings based on a format string. The format string can contain various directives that represent different components of the time, such as the year, month, day, hour, minute and second:
Ruby
time = Time.new(2026, 3, 25, 12, 30, 45)
# => 2026-03-25 12:30:45 +0000
time.strftime("%Y-%m-%d %H:%M:%S")
# => "2026-03-25 12:30:45"
time.strftime("%B %d, %Y")
# => "March 25, 2026"
time.strftime("%I:%M %p")
# => "12:30 PM"
time.strftime("%A, %B %d")
# => "Wednesday, March 25"
JavaScript
// Note: month is 0-based
const time = new Date(Date.UTC(2026, 2, 25, 12, 30, 45));
// => Wed Mar 25 2026 12:30:45 GMT+0000
time.toISOString().slice(0, 19).replace("T", " ");
// => "2026-03-25 12:30:45"
new Intl.DateTimeFormat("en-US", {
timeZone: "UTC",
month: "long",
day: "2-digit",
year: "numeric",
}).format(time);
// => "March 25, 2026"
new Intl.DateTimeFormat("en-US", {
timeZone: "UTC",
hour: "2-digit",
minute: "2-digit",
hour12: true,
}).format(time);
// => "12:30 PM"
new Intl.DateTimeFormat("en-US", {
timeZone: "UTC",
weekday: "long",
month: "long",
day: "2-digit",
}).format(time);
// => "Wednesday, March 25"
A complete list of the available directives can be found in the Ruby documentation.
History
Time#strftime was present in the very first version of Ruby, released in 1996.
The Time#strftime method is based on the C standard library function strftime, which was standardized in the C89 standard in 1989. The Ruby implementation of strftime follows the same format string syntax as the C version, which is why it has such a wide range of directives available.