【问题标题】:Rails undefined method `strftime' for "2013-03-06":StringRails 未定义方法“2013-03-06”的“strftime”:字符串
【发布时间】:2013-03-31 23:05:38
【问题描述】:

我收到了错误

“2013-03-06”的未定义方法 `strftime':String

尝试使用 strftime 从字符串 2013-03-06 正常显示日期(2013 年 6 月 3 日或类似日期)时。

在我的 index.html.erb 中执行此操作的行如下所示

<td><%= task.duedate.strftime("%B %e, %Y") %></td>

我只是在学习 Rails,所以我确信这只是一个愚蠢的初学者错误,任何帮助将不胜感激。谢谢

【问题讨论】:

  • 示例:d = Date.today # 2008-08-12 d.strftime('%b %d, %Y') # 将打印 2008 年 8 月 12 日
  • 您的到期日期字段不是 Date 或 DateTime 类型是否有特殊原因?
  • 我刚刚在迁移中添加和填充日期列后遇到了这个问题。解决方案只是重新启动(我猜 Rails 直到那时才知道属性是日期?)。

标签: ruby-on-rails ruby ruby-on-rails-3 strftime


【解决方案1】:

看起来你的到期日期是一个字符串,而 strftime 是 Time/Date 类的方法。你可以试试这个:

Date.parse(task.duedate).strftime("%B %e, %Y")

【讨论】:

    【解决方案2】:

    这为我解决了这个问题:

    Date.created_at.try(:strftime, ("%B %e, %Y"))
    

    希望这会有所帮助!

    【讨论】:

    • 这对我有用 - 因为有时值是 null ? 谢谢
    【解决方案3】:

    您将日期时间存储为字符串,而不是实际的日期时间。您将需要创建一个新的迁移,如下所示

    change_table :tasks do |t|  
      t.change :duedate, :datetime 
    end
    

    这样,当您访问到期日期时,它已经被解析为日期时间对象,而您不必每次都对其进行转换。

    【讨论】:

      【解决方案4】:

      您也可以使用 strptime。它对我有用:)

      DateTime.strptime(task.duedate ,"%B %e, %Y") 
      

      【讨论】:

        【解决方案5】:

        我也遇到了这个问题,在 controller.rb 文件中创建了一个将日期从字符串格式转换为 datetime 对象的方法后,我能够解决这个问题,然后在将数据保存到数据库之前,我在 create 函数中调用了这个方法。

          def convert_to_date(date_as_string)
            #expecting date format in "yyyy-mm-dd" format
            if date_as_string.length > 0
              split_date = date_as_string.split('-')
              return Date.new(year=split_date[0].to_i, month=split_date[1].to_i, 
              day=split_date[2].to_i) 
            else
              return nil 
            end 
          end 
        

        【讨论】:

          猜你喜欢
          • 2013-07-16
          • 1970-01-01
          • 2020-10-12
          • 1970-01-01
          • 1970-01-01
          • 2018-12-19
          • 1970-01-01
          • 1970-01-01
          • 2015-01-29
          相关资源
          最近更新 更多