简体   繁体   English

Rails日期转换,无效的日期错误

[英]Rails date conversion, invalid date error

I am POSTing data to my Rails API, one of the fields to be set on the created record looks like this: 我正在将数据发布到我的Rails API,要在创建的记录上设置的字段之一如下所示:

{
  "sign_date": "04/13/2015"
}

In my Rails API, I'm formatting it like so prior to the data being inserted: 在我的Rails API中,我在插入数据之前将其格式化为:

Date.strptime(params[:sign_date], "%m/%d/%Y").strftime("%Y-%m-%d")

However, Rails is spitting back an obscure Invalid Date error. 但是,Rails会吐出一个模糊的“ Invalid Date错误。 Must the data be of the type Date to create the record and have the date set properly? 数据是否必须为Date类型才能创建记录并正确设置日期?

What's wrong here? 怎么了

I get that error when I accidentally try to parse an empty string - check that your parameters are coming through correctly and where you expect them. 当我不小心尝试解析一个空字符串时,出现该错误-检查您的参数是否正确传递以及期望它们的位置。

> Date.strptime('', '%m/%d/%Y')
ArgumentError: invalid date

I hope this will work, 我希望这会起作用,

Try it in Rails Console . Rails Console中尝试一下。

Time.strptime("04/13/2015", "%m/%d/%Y").strftime("%Y-%m-%d")

#Output

"2015-04-13"

Try this Date.strptime(params["sign_date"], "%m/%d/%Y").strftime("%Y-%m-%d") 试试这个Date.strptime(params["sign_date"], "%m/%d/%Y").strftime("%Y-%m-%d")

For more details check Hash with indifferent access 有关更多详细信息,请检查访问权限无关的哈希

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

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