Rails undefined method `strftime' for “2013-03-06”:String

ε祈祈猫儿з 提交于 2019-12-22 04:38:25

问题


I am getting the error

undefined method `strftime' for "2013-03-06":String

when trying to display a date normally (June Sunday 3, 2013 or something similar) from the string 2013-03-06 using strftime.

The line that does this in my index.html.erb and looks like this

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

I am just learning Rails so I am sure it is just a stupid beginners error, any help would be appreciated. Thank you


回答1:


It looks like your duedate is a string, when strftime is a method for Time/Date class. You can try this:

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



回答2:


This solved the issue for me:

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

Hope this helps!




回答3:


You are storing the datetime as a string and not as an actually datetime. You will need to create a new migration like the following

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

This way when you access duedate it will have been already parsed as a datetime object, instead of you having to convert it everytime.




回答4:


You can also use strptime. It is working for me :)

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


来源:https://stackoverflow.com/questions/15735591/rails-undefined-method-strftime-for-2013-03-06string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!