「3rd」のように「rd」を含めるようにルビで日付をフォーマットするにはどうすればよいですか[重複]
質問
この質問にはすでに答えがあります:
「7月3日」や「10月1日」などの文字列を表示できるように日付オブジェクトを書式設定したいと考えています。Date.strftime に「rd」と「st」を生成するオプションが見つかりません。これを行う方法を知っている人はいますか?
解決
私は皆をエコーするつもりですが、あなただけのライブラリとしてそれを使用することができますので、私はちょうど、activesupport
の宝石をダウンロードすることをお勧めします。あなたは ordinalize
に使用するレールのすべてを必要としません。
% gem install activesupport ... % irb irb> require 'rubygems' #=> true irb> require 'activesupport' #=> true irb> 3.ordinalize #=> "3rd"
他のヒント
あなたが使用している場合を除き、のレールの、臆面もなくこのが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"
私は3回目のこのトピックを再訪していますので、私はいくつかの余分なコメント/利用状況と私の要点を更新しましたようです。
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.ordinal => 'STの
1.ordinalize => '第1回'
所属していません StackOverflow