Search code examples
ruby-on-railsdatetimebootstrap-datetimepickerstrptime

Why does this work in console buy not in my app?


I tried to solve this problem a thousand different ways looking at dozens of StackOverflow posts as well as outside tutorials dealing with DateTime, bootstrap datetimepicker, formatting, strptime, strftime, and on and on, without resolution. I have one basic question right now that may help me move forward.

Why does this work in my console:

 DateTime.strptime("09-29-2016 03:29 PM", "%m-%d-%Y %I:%M %p")
   => Thu, 29 Sep 2016 15:29:00 +0000 

But this fails in my app:

@image.start_at = DateTime.strptime(params[:start_at].to_s, "%m-%d-%Y %I:%M %p")
=>ArgumentError in ImagesController#create
invalid date

My start_at parameters come through as:

..."start_at"=>"09-29-2016 03:29 PM"},... 

Also, this doesn't work in my app:

@image.start_at = DateTime.strptime(@image.start_at.to_s, "%m-%d-%Y %I:%M %p")

Solution

  • This should work just fine:

    @image.start_at = Date.strptime(params[:image][:start_at], "%m-%d-%Y %I:%M %p")
    

    Explanation:

    1. you do not have to convert it to string - anything in params IS a String;
    2. since the start_at's type is a Date, you should pass a Date object to it, not a DateTime object.

    If your start_at IS a datetime type (not date, as you've said in comments),

    @image.start_at = DateTime.strptime(params[:image][:start_at], "%m-%d-%Y %I:%M %p")

    will work.