我想格式化一个日期对象,以便我可以显示诸如"7月3日"或"10月1日"之类的字符串.我在Date.strftime中找不到生成"rd"和"st"的选项.有人知道怎么做吗?
Lar*_*eth 39
除非您使用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
Bar*_*her 24
created_at.strftime("#{created_at.day.ordinalize} of %m, %y")
将产生"2009年7月4日"
ram*_*ion 24
我会回应其他人,但我会鼓励你下载activesupportgem,所以你可以把它当作一个库.您不需要使用所有Rails ordinalize.
% gem install activesupport ... % irb irb> require 'rubygems' #=> true irb> require 'activesupport' #=> true irb> 3.ordinalize #=> "3rd"
| 归档时间: | 
 | 
| 查看次数: | 14416 次 | 
| 最近记录: |