【问题标题】:Grab Just the Month from date converted to string从转换为字符串的日期中获取月份
【发布时间】:2013-07-22 12:23:46
【问题描述】:

我正在尝试将日期转换为字符串,然后获取该月的前 3 个字符,以便在我的视图中使用它。例如,我的日期看起来像这样

23-07-2013

我有一个方法(可能完全错误),但我无法得到任何输出,尽管在 irb 中这是可行的。这就是我所拥有的

def date_mon(date)
 str = date.strftime("%e %B %Y") if date
 arr = str.split('-')
 arr[3-5]
end

那么在我看来

<%= date_mon(p.created_at) %>

在这种情况下我想要展示的是

Jul

任何关于我哪里出错的指针?

谢谢

【问题讨论】:

    标签: ruby ruby-on-rails-3 string methods


    【解决方案1】:
    def date_mon(date)
      date.strftime("%b")
    end
    

    【讨论】:

      【解决方案2】:

      当您执行split 时,创建的数组有 2 个位置。因此,您必须仅在数组的第一个位置搜索 3 到 5 个字符:

      arr[0][3..5]
      

      【讨论】:

        【解决方案3】:

        或者你可以直接做

        <%= p.created_at.strftime("%b") %>
        

        【讨论】:

          猜你喜欢
          • 2021-01-25
          • 1970-01-01
          • 2016-10-14
          • 2020-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多