Rails undefined method `strftime' for "2013-03-06":String
Asked Answered
P

5

10

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

Patrizius answered 31/3, 2013 at 23:5 Comment(3)
Example: d = Date.today # 2008-08-12 d.strftime(‘%b %d, %Y’) # will print August 12, 2008Bell
Is there a special reason why your duedate field is not of the Date or DateTime types?Electrolyse
I just ran into this issue after adding and populating a date-column in a migration. The solution was simply restarting (I guess Rails didn't know the attribute was a date until then?).Hyla
S
41

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")
Seedling answered 31/3, 2013 at 23:16 Comment(0)
G
2

This solved the issue for me:

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

Hope this helps!

Gallegos answered 29/4, 2017 at 1:48 Comment(1)
This worked for me - since sometimes values are a null 😁 Thank youLated
P
0

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.

Phratry answered 31/3, 2013 at 23:12 Comment(0)
S
0

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

DateTime.strptime(task.duedate ,"%B %e, %Y") 
Slag answered 12/7, 2016 at 10:7 Comment(0)
D
0

I faced this issue as well and I was able to solve it after creating a method in controller.rb file which converted date from string format to datetime object I then called this method in create function before saving the data into database.

  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 
Donall answered 15/5, 2021 at 19:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.