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

Lau*_*ung 23 ruby strftime

我想格式化一个日期对象,以便我可以显示诸如"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
Run Code Online (Sandbox Code Playgroud)

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

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


Bar*_*her 24

created_at.strftime("#{created_at.day.ordinalize} of %m, %y")
Run Code Online (Sandbox Code Playgroud)

将产生"2009年7月4日"

  • 当您需要使用非典型的“7 月 4 日”格式时,这很好,但如果您使用传统的“2009 年 7 月 4 日”格式,则无需手动排序:`created_at.to_date.to_s(:long_ordinal)`。 (2认同)

ram*_*ion 24

我会回应其他人,但我会鼓励你下载activesupportgem,所以你可以把它当作一个库.您不需要使用所有Rails ordinalize.

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

  • 好点子.您还可以从facets(http://facets.rubyforge.org)库中获取此功能 - 需要'facets'或者,对于此方法,需要'facets/integer/ordinal' (2认同)
  • 有一种更简单的方法可以获取您想要的内容,而无需手动操作日期整数:“date.to_s(:long_ordinal)”。请参阅:http://api.rubyonrails.org/classes/Date.html#method-i-to_formatted_s (2认同)

wai*_*wai 8

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

puts 3.ordinalize #=> "3rd"
Run Code Online (Sandbox Code Playgroud)