【发布时间】:2010-11-08 02:10:30
【问题描述】:
我想格式化一个日期对象,以便可以显示诸如“3rd July”或“1st October”之类的字符串。我在 Date.strftime 中找不到生成“rd”和“st”的选项。有人知道怎么做吗?
【问题讨论】:
我想格式化一个日期对象,以便可以显示诸如“3rd July”或“1st October”之类的字符串。我在 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
【讨论】:
Integer class.
created_at.strftime("#{created_at.day.ordinalize} of %m, %y")
将制作“2009 年 7 月 4 日”
【讨论】:
created_at.to_date.to_s(:long_ordinal)。
我将回应其他所有人,但我只是鼓励您下载activesupport gem,这样您就可以将其用作库。你不需要所有的 Rails 都可以使用ordinalize。
【讨论】:
3<span>th</span>
3.ordinalize.sub(/\w+/, '<span>\0</span>')
date.to_s(:long_ordinal)。见:api.rubyonrails.org/classes/Date.html#method-i-to_formatted_s
我认为 Ruby 没有,但如果你有 Rails,试试这个:-
puts 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>
【讨论】:
需要“主动支持”
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。
【讨论】: