pencil writing a date
software development ruby engineering
December 9th, 2021 - Erhan Berber

Formatting Dates in Ruby

We've noticed that some functions, like strftime, are altogether difficult to find those pesky options we need but can't remember. Formatting dates in ruby is one of those functions that we just need a cheat sheet - so we created this. If we are being real, this post is basically for us to reference. But we're happy for you to do so as well.

When would you need to format dates in Ruby?

Essentially, you'll probably need to format the dates in Ruby whenever the application calls for a date to be displayed specifically. For instance, if you are coding a date picker for an application that services multiple countries. For users in the United States you'd want the month first, users in nearly every other country would expect the day then the month in the display.

How do you format dates in Ruby?

Now to the thick of it. When converting Date and DateTime objects to strings for display using a function like strftime, here's the handy reference sheet for the options you can use to format output.

Here's an example implementation to display a date in the m/dd/yyyy format.

> the_date.strftime('%m/%d/%Y')
=> 12/10/2021

Ruby Date and Time strftime Format Options

Format Description Example
%b Shortened month name "Jan"
%B Full month name "January"
%m Numbered month of the year (01..12) "01"
%d Day of the month (01..31) "15"
%j Day of the year (001..366) "123"
%a Shortened weekday name "Mon"
%A Full weekday name "Monday"
%w The numeric day of the week (0..6) "1"
%U Numeric week number in the year (0..53) [starting with the first Sunday] "22"
%W Numeric week number in the year (0..53) [starting with the first Monday] "22"
%y Two-digit year (00..99) "99"
%Y Four-digit year "2022"
%H Hour of the day (military time) (00..23) "18"
%I Hour of the day (12-hour clock) (01..12) "08"
%M Minute of the hour (0..59) "15"
%S Second of the minute (0..59) "30"
%p AM or PM "PM"
%Z Time zone name "Central Time (US & Canada)"