Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is causing this invalid date error?

On 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 parameters:

{
  "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 is causing this error? Thanks for reading.

like image 819
ben Avatar asked Nov 29 '10 06:11

ben


People also ask

What is the meaning of invalid date?

The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to Date or Date.

What does invalid time value mean?

Conclusion # The "Uncaught RangeError: Invalid time value" error occurs when calling a method on an invalid date, e.g. new Date('asdf'). toISOString() . To solve the error, conditionally check if the date is valid before calling the method on it.


2 Answers

The parameters you are getting is

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

Hence we can clearly make out

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

UPDATE

Date.strptime method follows a particular pattern.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")
like image 50
Rohit Avatar answered Oct 20 '22 21:10

Rohit


Use to_date method to format params[:custom_date]

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

Thanks

like image 1
Anubhaw Avatar answered Oct 20 '22 22:10

Anubhaw