What causes this invalid date error?

In this line of code:

@note.date = Date.strptime(params[:custom_date], '%d-%m-%Y') unless params[:custom_date].blank? 

I get this error:

 ArgumentError: invalid date /usr/ruby1.9.2/lib/ruby/1.9.1/date.rb:1022 

Here are the options:

 { "commit" => "Create", "utf8" => "\342\234\223", "authenticity_token" => "RKYZNmRaElg/hT5tlmLcqnstnOapdhiaWmDcjNDtSOI=", "action" => "create", "note" => { "name"=>"note1", "detail"=>"detail" }, "controller" => "notes", "custom_date" => "03-03-2010" } 

What causes this error? Thank you for reading.

+4
source share
3 answers

The options you get are

 {"commit"=>"Create", "utf8"=>"\342\234\223", "authenticity_token"=>"RKYZNmRaElg/hT5tlmLcqnstnOapdhiaWmDcjNDtSOI=", "action"=>"create", "note"=> {"name"=>"note1", "detail"=>"detail"}, "controller"=>"notes", "custom_date"=>"03-03-2010"} 

This clearly shows that

its not params[:custom_date] , but it is params['custom_date']

UPDATE

The Date.strptime method follows a specific template. for instance

 str = "01-12-2010" #DD-MM-YYYY then use Date.strptime(str,"%d-%m-%Y") 

but if

 str = "2010-12-01" #YYYY-MM-DD then use Date.strptime(str,"%Y-%m-%d") 
+10
source

Use the to_date method to format parameters [: custom_date]

 @note.date = (Date.strptime(params[:custom_date], '%d-%m-%Y')).to_date unless params[:custom_date].blank? 

thanks

+1
source

I can not reproduce this error on ruby ​​1.9.2 or ruby ​​1.8.7

I suspect your parameter [: custom_date] is changing between the displayed log output and the displayed call to Date.strptime.

Rails symbolizes params keys, so they can be read as params [: custom_date]

0
source

All Articles