我得到错误
未定义的方法' strftime'为"2013-03-06":字符串
当尝试使用strftime从字符串2013-03-06中正常显示日期(June Sunday 3,2013或类似的东西)时。
在我的index.html.erb中执行此操作的行,看起来像这样
<td><%= task.duedate.strftime("%B %e, %Y") %></td>
我刚刚学习Rails,所以我确信这只是一个愚蠢的初学者错误,任何帮助都会很感激。谢谢你
看起来您的duedate是一个字符串,而strftime是时间/日期类的方法。你可以试试:
Date.parse(task.duedate).strftime("%B %e, %Y")
这为我解决了这个问题:
Date.created_at.try(:strftime, ("%B %e, %Y"))
希望这对你有帮助!
您将日期时间存储为字符串而不是实际的日期时间。您将需要创建一个新的迁移,如下所示
change_table :tasks do |t|
t.change :duedate, :datetime
end
这样,当您访问duedate时,它将已经被解析为datetime对象,而不必每次都转换它。
您也可以使用strptime。它正在为我工作:)
DateTime.strptime(task.duedate ,"%B %e, %Y")
我也面临这个问题,我能够在控制器中创建方法后解决它。在将数据保存到数据库之前,我在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