如何在ruby中格式化日期以包含“rd”,如“3rd”

我想格式化一个日期对象,以便我可以显示诸如“7月3日”或“10月1日”之类的字符串。 我在Date.strftime中找不到生成“rd”和“st”的选项。 有人知道怎么做吗?

我要activesupport其他人,但我会鼓励你下载activesupport gem,这样你就可以把它当作一个库。 您不需要所有Rails都使用ordinalize

 %gem install activesupport
 ...
 %irb 
 irb> require'rubygems'
 #=>是的
 irb> require'activesupport'
 #=>是的
 irb> 3.ordinalize
 #=>“第三”

除非您使用Rails ,否则请将此ordinalize方法(从Rails源无耻地提取的代码)添加到Fixnum

 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 

然后像这样格式化你的日期:

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

将产生“2009年7月4日”

我不认为Ruby有它,但如果你有Rails,试试这个: –

 puts 3.ordinalize #=> "3rd" 

似乎我第三次重新审视这个话题,所以我用一些额外的评论/用法更新了我的要点。

https://gist.github.com/alterisian/4154152

干杯,伊恩。

我不知道它是否比switch-case更快(任何?),但我用结尾做了一个常数:

 DAY_ENDINGS = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"] 

然后就像使用它一样:

 DAY_ENDINGS[date.mday] 

正如我想要的结局

 th 

需要’activesupport’
1.ordinal =>’st’
1.ordinalize =>’1st’