How do I format a date in ruby to include "rd" as in "3rd"

Laurie Young picture Laurie Young · Jul 4, 2009 · Viewed 15.6k times · Source

I want to format a date object so that I can display strings such as "3rd July" or "1st October". I can't find an option in Date.strftime to generate the "rd" and "st". Any one know how to do this?

Answer

Lars Haugseth picture Lars Haugseth · Jul 4, 2009

Unless you're using Rails, add this ordinalize method (code shamelessly lifted from the Rails source) to the Fixnum class

class Fixnum
  def ordinalize
    if (11..13).include?(self % 100)
      "#{self}th"
    else
      case self % 10
        when 1; "#{self}st"
        when 2; "#{self}nd"
        when 3; "#{self}rd"
        else    "#{self}th"
      end
    end
  end
end

Then format your date like this:

> now = Time.now
> puts now.strftime("#{now.day.ordinalize} of %B, %Y")
=> 4th of July, 2009