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?
+6
A:
Hello, I don't think Ruby has it, but if you have Rails, try this:-
puts 3.ordinalize #=> "3rd"
wai
2009-07-04 10:34:25
It's also available in Facets.
Pesto
2009-07-06 02:08:01
+1
A:
created_at.strftime("#{created_at.day.ordinalize} of %m, %y")
Will produce "4th of July, 2009"
Barry Gallagher
2009-07-04 10:43:58
+10
A:
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
Lars Haugseth
2009-07-04 12:08:04
+5
A:
I'm going to echo everyone else, but I'll just encourage you to download the activesupport
gem, so you can just use it as a library. You don't need all of Rails to use ordinalize
.
% gem install activesupport ... % irb irb> require 'rubygems' #=> true irb> require 'activesupport' #=> true irb> 3.ordinalize #=> "3rd"
rampion
2009-07-04 17:56:20
Good point. You can also get this functionality from the facets (http://facets.rubyforge.org) library - require 'facets' or, for just this method, require 'facets/integer/ordinal'
Greg Campbell
2009-07-05 17:42:14