【问题标题】:Create an array of months and year in rails在 Rails 中创建一系列月份和年份
【发布时间】:2021-11-14 00:32:09
【问题描述】:

我需要创建一个这样的数组

[“2020年1月、2020年2月、2020年3月、2020年4月、2020年5月、2020年6月,以此类推直到上个月]

使用 Date::MONTHNAMES,它只枚举月份,但我找不到添加年份的方法。 谢谢,

【问题讨论】:

    标签: arrays ruby-on-rails date select


    【解决方案1】:

    你可以使用map方法。

    month_names = Date::MONTHNAMES.compact.map{ |m| "#{m} #{Time.zone.now.year}" }
    p month_names
    #=> ["January 2021", "February 2021", "March 2021", "April 2021",
         "May 2021", "June 2021", "July 2021", "August 2021", "September 2021",
         "October 2021", "November 2021", "December 2021"]
    

    【讨论】:

      【解决方案2】:

      您可以简单地映射它并添加当前年份,例如 Date::MONTHNAMES.compact.map{ |month| "#{month} #{Date.current.year}" }

      【讨论】:

        【解决方案3】:

        我会选择:

        def month_names(year)
          1.upto(12).map |month|
            Date.new(year, month).strftime("%b %Y")
          end
        end
        

        虽然与简单的字符串连接相比,这似乎有点过头了,但您可以轻松地将 strftime 替换为 I18n 模块以对其进行本地化。

        def month_names(year)
          1.upto(12).map |month|
            I18n.localize(Date.new(year, month), format: :long)
          end
        end
        
        # config/locale/pirate.yml
        pirate:
          date:
            formats:
              long: "Aargh! it be the on the fair month of %m %Y"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多