【问题标题】:Suffixes on dates (1st, 2nd, 3rd, 4th etc) [duplicate]日期后缀(第 1、第 2、第 3、第 4 等)[重复]
【发布时间】:2013-10-21 06:54:49
【问题描述】:

我正在编写一个脚本来将 IPTC 数据添加到图像文件夹中。它从 EXIF 信息中提取日期并将其添加到 'Caption' IPTC 标记中。

date = iptc["DateTimeOriginal"]
date = date.strftime('%A %e %B %Y').upcase
iptc["Caption"] = '%s: %s (%s)' % [date, caption, location]

除了日期输出之外,脚本可以工作:

Sunday 13 October 2013

理想情况下,我希望它输出:

Sunday 13th October 2013

任何建议将不胜感激。

【问题讨论】:

    标签: ruby string date format


    【解决方案1】:

    如果您能够(并且愿意)将 Ruby gem 加入其中,请考虑使用ActiveSupport::Inflector。 您可以使用

    安装它

    gem install active_support

    (你可能需要sudo

    然后在你的文件中要求它并包含ActiveSupport::Inflector:

    require 'active_support/inflector' # loads the gem
    include ActiveSupport::Inflector # brings methods to current namespace
    

    那么你就可以ordinalize integers willy-nilly:

    ordinalize(1)  # => "1st"
    ordinalize(13) # => "13th"
    

    不过,您可能必须手动将日期字符串化:

    date = iptc["DateTimeOriginal"]
    date_string = date.strftime('%A ordinalday %B %Y')
    date_string.sub!(/ordinalday/, ordinalize(date.day))
    date_string.upcase!
    

    你应该在路上了:

    iptc["Caption"] = "#{date_string}: #{caption} #{location}"
    

    【讨论】:

    • 已解决,在最后一点稍作调整:将 {date} 更改为 {date_string} 会给出正确的输出。非常感谢!
    • 正确!我的错 - 相应更新!
    【解决方案2】:

    如果您不想要求 ActiveSupport 的帮助程序,也许只需复制一种特定的方法来完成这项工作:

    # File activesupport/lib/active_support/inflector/methods.rb
    def ordinalize(number)
      if (11..13).include?(number.to_i.abs % 100)
        "#{number}th"
      else
        case number.to_i.abs % 10
          when 1; "#{number}st"
          when 2; "#{number}nd"
          when 3; "#{number}rd"
          else    "#{number}th"
        end
      end
    end
    

    在脚本中使用该方法,将代码更改为:

    date = date.strftime("%A #{ordinalize(date.day)} %B %Y")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2021-05-14
      • 1970-01-01
      • 2021-05-31
      相关资源
      最近更新 更多