In Ruby on Rails, how do I format a date with the "th" suffix, as in, "Sun Oct 5th"? In Ruby on Rails, how do I format a date with the "th" suffix, as in, "Sun Oct 5th"? ruby ruby

In Ruby on Rails, how do I format a date with the "th" suffix, as in, "Sun Oct 5th"?


Use the ordinalize method from 'active_support'.

>> time = Time.new=> Fri Oct 03 01:24:48 +0100 2008>> time.strftime("%a %b #{time.day.ordinalize}")=> "Fri Oct 3rd"

Note, if you are using IRB with Ruby 2.0, you must first run:

require 'active_support/core_ext/integer/inflections'


You can use active_support's ordinalize helper method on numbers.

>> 3.ordinalize=> "3rd">> 2.ordinalize=> "2nd">> 1.ordinalize=> "1st"


Taking Patrick McKenzie's answer just a bit further, you could create a new file in your config/initializers directory called date_format.rb (or whatever you want) and put this in it:

Time::DATE_FORMATS.merge!(  my_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") })

Then in your view code you can format any date simply by assigning it your new date format:

My Date: <%= h some_date.to_s(:my_date) %>

It's simple, it works, and is easy to build on. Just add more format lines in the date_format.rb file for each of your different date formats. Here is a more fleshed out example.

Time::DATE_FORMATS.merge!(   datetime_military: '%Y-%m-%d %H:%M',   datetime:          '%Y-%m-%d %I:%M%P',   time:              '%I:%M%P',   time_military:     '%H:%M%P',   datetime_short:    '%m/%d %I:%M',   due_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") })