什么导致了这个无效日期错误?

6

在这行代码中:

@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

以下是参数:

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

什么导致了这个错误?谢谢阅读。
3个回答

13
您获取的参数是:
{"commit"=>"Create",
 "utf8"=>"\342\234\223",
 "authenticity_token"=>"RKYZNmRaElg/hT5tlmLcqnstnOapdhiaWmDcjNDtSOI=",
 "action"=>"create",
 "note"=>
  {"name"=>"note1",
   "detail"=>"detail"},
 "controller"=>"notes",
 "custom_date"=>"03-03-2010"}
因此,我们可以清楚地看出,它不是params[:custom_date],而是params['custom_date']更新: Date.strptime方法遵循特定的模式。例如:
str = "01-12-2010" #DD-MM-YYYY
then use
Date.strptime(str,"%d-%m-%Y")

但是如果

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

1
使用 to_date 方法格式化 params[:custom_date]。
@note.date = (Date.strptime(params[:custom_date], '%d-%m-%Y')).to_date unless params[:custom_date].blank?   

谢谢


1
添加 to_date 是多余的。Date.strptime(...) 已经返回一个 Date 对象了。 - the Tin Man

0

我无法在Ruby 1.9.2或Ruby 1.8.7上重现此错误。

我怀疑您的param[:custom_date]在日志输出和Date.strptime调用之间发生了变化。

Rails将params键转换为符号,因此可以将它们读取为params[:custom_date]。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接