微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用daystrftimeDateTime红宝石生成'th'或'st'输出

如何解决如何使用daystrftimeDateTime红宝石生成'th'或'st'输出

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

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

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

解决方法

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

  • %e模式是用空格填充的,这确实导致间距不连续(使用%-d
  • 扩展案例声明以处理每月两位数字(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,2))
p format(Time.new(2020,3))
p format(Time.new(2020,4))
p format(Time.new(2020,11))
p format(Time.new(2020,12))
p format(Time.new(2020,13))
p format(Time.new(2020,14))
p format(Time.new(2020,21))
p format(Time.new(2020,22))
p format(Time.new(2020,23))
p format(Time.new(2020,24))
p format(Time.new(2020,30))
p format(Time.new(2020,31))
,

在哈希表中映射序数;将11-13作为特殊情况处理

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

对于大多数值,您可以通过在月的某天应用Integer#modulo(10)在下面的 ordinals 哈希中查找正确的后缀。模运算有效地为您提供了当月有效日期的最后一位数字,我们将使用该数字作为哈希键来检索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"
,

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。