我想格式化一个日期对象,以便显示类似于“7月3日”或“10月1日”的字符串。 我在 Date.strftime 中找不到生成“rd”和“st”的选项。 有人知道怎么做吗?
如果你不使用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日"
created_at.to_date.to_s(:long_ordinal)
。 - Olivier Lacan我会跟大家一样强烈建议你下载 activesupport
gem, 然后将其作为一个库使用。你不需要安装整个 Rails 来使用ordinalize
。
% gem install activesupport ... % irb irb> require 'rubygems' #=> true irb> require 'activesupport' #=> true irb> 3.ordinalize #=> "3rd"
3.ordinalize.sub(/\w+/, '<span>\0</span>')
- rampiondate.to_s(:long_ordinal)
。详情请参见:http://api.rubyonrails.org/classes/Date.html#method-i-to_formatted_s - Olivier Lacanputs 3.ordinalize #=> "3rd"
我不知道这是否比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]
<span>th</span>
需要 'activesupport' 库
1.ordinal => 'st'
1.ordinalize => '1st'
require 'time'
H = Hash.new do |_,k|
k +
case k
when '1', '21', '31'
'st'
when '2', '22'
'nd'
when '3', '23'
'rd'
else
'th'
end
end
def fmt_it(time)
time.strftime("%A %-d, %-l:%M%P").sub(/\d+(?=,)/, H)
end
fmt_it(Time.new)
#=> "Wednesday 9th, 1:36pm"
fmt_it(Time.new + 3*24*60*60)
#=> "Saturday 12th, 3:15pm"
我使用了String#sub的形式(也可以使用sub!
),它将哈希表(H
)作为其第二个参数。
sub
使用的正则表达式是“匹配一个或多个数字,后跟逗号”。(?=,)
是一个正向先行断言。
我使用了Hash::new的形式创建了(空的)哈希表H
,该形式需要一个块。这意味着如果H
没有键k
,则H[k]
返回块计算出的值。在这种情况下,哈希表为空,因此块始终返回感兴趣的值。该块接受两个参数:哈希表(这里是H
)和正在评估的键。我用下划线表示前者,表示块不使用它。以下是一些示例:
H['1'] #=> "1st"
H['2'] #=> "2nd"
H['3'] #=> "3rd"
H['4'] #=> "4th"
H['9'] #=> "9th"
H['10'] #=> "10th"
H['11'] #=> "11th"
H['12'] #=> "12th"
H['13'] #=> "13th"
H['14'] #=> "14th"
H['22'] #=> "22nd"
H['24'] #=> "24th"
H['31'] #=> "31st"
查看 Time#strftime 以获取格式化指令。
Integer
类的扩展。 - Dennis