是什麼導致了這個無效的日期錯誤? (What is causing this invalid date error?)


問題描述

是什麼導致了這個無效的日期錯誤? (What is causing this invalid date error?)

在這行代碼上:

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

我收到此錯誤:

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

是什麼導致了這個錯誤?感謝閱讀。


參考解法

方法 1:

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

方法 2:

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

方法 3:

I'm not able to reproduce this error on ruby 1.9.2 or ruby 1.8.7

I suspect that your param[:custom_date] changes between the log output u've shown and the Date.strptime call.

Rails symbolizes the params keys so it's possible to read them as params[:custom_date]

(by benRohitAnubhawAditya Sanghi)

參考文件

  1. What is causing this invalid date error? (CC BY‑SA 3.0/4.0)

#Date #ruby-on-rails #ruby






相關問題

MySQL WHERE 時間戳 >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY) (MySQL WHERE timestamp >= SUBDATE(MAX(timestamp), INTERVAL 5 DAY))

需要有關排序要求的幫助 (Need assistance with a usort requirement)

在 Java 日期/日曆對像中發現神秘的毫秒數 (Mysterious milliseconds number found in Java Date/Calendar object)

按日期子集 data.frame (Subset data.frame by date)

根據添加到頁面的內容更改 div 類 (change div class based on content added to page)

我應該如何設置日期? (How should I set the date?)

日期的 Drupal 8 上下文過濾器 (Drupal 8 contextual filter for date)

是什麼導致了這個無效的日期錯誤? (What is causing this invalid date error?)

按存儲在文本列中的日期排序表 (Order table by date stored in text column)

如何啟用靜態時間但仍有動態日期? (How do I enable a static time but still have dynamic date?)

是否可以在日期列中加載各種格式的數據?甲骨文 (is that possible to load data of various format in date column | Oracle)

MongoDB/Mongoose 時區日期遞減問題 (MongoDB/Mongoose timezone date decrement problem)







留言討論