【问题标题】:How to generate the 'th' or 'st' output using the daystrftime (DateTime) ruby [duplicate]如何使用daystrftime(DateTime)ruby生成'th'或'st'输出[重复]
【发布时间】:2020-12-28 05:36:25
【问题描述】:

如何使用daystrftime -> (DateTime) 方法生成Wednesday 9th, 9:24pm

我正在使用Time.now.strftime("%A%e, %l:%M%P"),输出为Wednesday 9, 9:24pm 但是如何添加thnd 后缀?

理想的输出应该是Wednesday 9th, 9:24pmWednesday 2nd, 9:24pmWednesday 1st, 9:24pm

【问题讨论】:

  • 读者:在问题被关闭之前,这里发布的一些答案作为一个副本已经发布在the question,因为这个问题被发现是一个副本。

标签: ruby datetime


【解决方案1】:

扩展@steenslag 的答案以解决两个问题:

  • %e 模式是用空格填充的,这会导致间距不一致(使用 %-d
  • 扩展 case 语句以处理两位数的月份日期 (21 - 31)
def format(time)
  time.strftime("%A %-d, %l:%M%P").sub!(/\d?\d/) do |day|
    case day
    when "1", "21", "31" then "#{day}st"
    when "2", "22" then "#{day}nd"
    when "3", "23" then "#{day}rd"
    else "#{day}th"
    end
  end
end


p format(Time.new(2020, 1, 1))
p format(Time.new(2020, 1, 2))
p format(Time.new(2020, 1, 3))
p format(Time.new(2020, 1, 4))
p format(Time.new(2020, 1, 11))
p format(Time.new(2020, 1, 12))
p format(Time.new(2020, 1, 13))
p format(Time.new(2020, 1, 14))
p format(Time.new(2020, 1, 21))
p format(Time.new(2020, 1, 22))
p format(Time.new(2020, 1, 23))
p format(Time.new(2020, 1, 24))
p format(Time.new(2020, 1, 30))
p format(Time.new(2020, 1, 31))

【讨论】:

  • 是的,这样更好。
【解决方案2】:

哈希中的映射序数;将 11-13 作为特例处理

可能有一种更优雅的方式来执行此操作,但通常您需要为所需的序数后缀定义自己的映射。特别是需要特别处理11-13。例如,13th23rd 有不同的序数后缀,尽管它们都以 3 结尾。

对于大多数值,您可以通过将Integer#modulo(10) 应用于月份的日期,在下面的序数 哈希中查找正确的后缀。在处理月份的有效日期时,模运算有效地为您提供了最后一位数字,我们将使用该数字作为哈希键来检索 String#sub 的正确后缀。

以下代码突出显示了这种方法。

ordinals = { 
  1 => 'st',
  2 => 'nd',
  3 => 'rd',
  4 => 'th',
  5 => 'th',
  6 => 'th',
  7 => 'th',
  8 => 'th',
  9 => 'th',
  0 => 'th',
}

str        = 'Wednesday 9, 9:24pm'
date_expr  = /\d+(?=,)/
date       = str.match(date_expr).to_s.to_i
ord_suffix = case date
             when 11..13 then 'th'
             else ordinals[date % 10] 
             end 

str.sub date_expr, "#{date}#{ord_suffix}"
#=> "Wednesday 9th, 9:24pm"

【讨论】:

  • 一个很好的答案,不幸的是很多人不会看到。我鼓励您在未结束的问题上发布此内容,以提高其知名度。
  • 请注意,之前的纯 Ruby 解决方案已经重新开放。
【解决方案3】:

正如这个答案中所建议的 - link 我们可以在这里使用类似的方法:

time = Time.new
time.strftime("%A #{time.day.ordinalize},%l:%M%P") -> Wednesday 9th, 4:10pm

【讨论】:

  • 我建议你指出,如果没有使用 Rails,需要require 'active_support/core_ext/integer/inflections'
猜你喜欢
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多