简体   繁体   English

导致此无效日期错误的原因是什么?

[英]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. 谢谢阅读。

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'] 它不是params[:custom_date]但它是params['custom_date']

UPDATE UPDATE

Date.strptime method follows a particular pattern.For instance Date.strptime方法遵循特定模式。例如

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")

Use to_date method to format params[:custom_date] 使用to_date方法格式化params [:custom_date]

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

Thanks 谢谢

I'm not able to reproduce this error on ruby 1.9.2 or ruby 1.8.7 我无法在ruby 1.9.2或ruby 1.8.7上重现此错误

I suspect that your param[:custom_date] changes between the log output u've shown and the Date.strptime call. 我怀疑你的param [:custom_date]在你显示的日志输出和Date.strptime调用之间发生了变化。

Rails symbolizes the params keys so it's possible to read them as params[:custom_date] Rails表示params键,因此可以将它们读为params [:custom_date]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM