rails change date format before saving to mysql DB

丶灬走出姿态 提交于 2019-12-22 09:49:26

问题


I have a datepicker that I want to display in MM/DD/YYYY. However I'm using a mysql db which wants YYYY-MM-DD. As it stands right now its saving but the day and month are being reversed.

Right now I have an initalizer, date_time_formats.rb which has:

Date::DATE_FORMATS[:default] = '%m/%d/%Y'

Also in my datepicker jscript I have the correct format which I want to display:

$(this).datepicker({"format": "mm/dd/yyyy", "weekStart": 0, "autoclose": true, "startDate":new Date()});

I've tried things like this:

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

But I get a HashWithIndifferentAccess error.

How can I reformat the date in the params hash prior to assigning to an instance of the model? The reason being it seems to get rejected from the model if the date would be invalid (ex. April 4, 2013 is fine, but April 20, 2013 is not because there is no 20th month). I'm a big time rails novice so maybe I'm wrong but thats how it appears to be working. Thanks!


回答1:


try the american_date gem located here: https://github.com/jeremyevans/ruby-american_date




回答2:


Look up the strftime method of the various date classes. The incantation you want is Time.local(params[:location]).strftime('%m/%d/%Y'), hope that helps!




回答3:


A quick way to sanitize the date to the correct format is to grab it in the controller before it gets saved and use strftime to correct the format. For example:

@model = Model.new(model_params)
@model.date_you_want = @model.date_you_want.strftime('%Y/%d/%m')
@model.save

This saves the date in the correct format. (I'm also using datepicker-boostrap gem)



来源:https://stackoverflow.com/questions/15538413/rails-change-date-format-before-saving-to-mysql-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!