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

I get an error

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

when trying to display the date usually (June 3, 2013 or something similar) from the line 2013-03-06 using strftime.

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

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

I'm just learning Rails, so I'm sure this is just a dumb beginner mistake, any help would be appreciated. Thanks you

+7
source share
4 answers

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

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

This solved the problem for me:

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

, !

+1

You save the date-time as a string, and not as the actual time. You will need to create a new migration as shown below.

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

That way, when you access duedate, it will already be parsed as a datetime object, instead of converting it every time.

0
source

You can also use strptime. It works for me :)

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

All Articles