这个问题已经有一个答案在这里:

我想到日期的格式对象,这样我可以显示串如"3日"或"1st十月"。我不能找到一个选项的日期。strftime产生的"rd"和"st".任何一个知道如何做到这一点?

有帮助吗?

解决方案

我要回所有的人,但我只会鼓励你下载的 activesupport 宝石,所以你可以用它作为一个图书馆。你不需要所有轨道的使用 ordinalize.

% gem install activesupport
...
% irb 
irb> require 'rubygems'
#=>  true
irb> require 'activesupport'
#=>  true
irb> 3.ordinalize
#=>  "3rd"

其他提示

除非你使用 , 添加这个 ordinalize 方法(代码无耻 解除从轨源)来的 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")

将产生"第4月,2009年"

我不认为红宝石都有它,但是如果你有轨道,试试这个:-

puts 3.ordinalize #=> "3rd"

看来我重新审视这一主题的第三次,所以我已经更新我的要旨有一些额外的评论/使用情况。

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

干杯, 伊恩。

我不知道,如果它使得多的(任何?) 快于交换情况的,但我做了一个恒定与结局:

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]

因为我想要的结局内部

<span>th</span>

需要'activesupport'
1.序=>"st"
1.ordinalize=>'1'

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top