简体   繁体   中英

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:

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

In my Rails API, I'm formatting it like so prior to the data being inserted:

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

However, Rails is spitting back an obscure Invalid Date error. Must the data be of the type Date to create the record and have the date set properly?

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 .

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

For more details check Hash with indifferent access

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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