rails在保存到mysql DB之前更改日期格式 [英] rails change date format before saving to mysql DB

查看:81
本文介绍了rails在保存到mysql DB之前更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我要显示在MM / DD / YYYY的日期戳。但是我正在使用一个需要YYYY-MM-DD的mysql数据库。现在它的保存,但日期和月份正在逆转。



现在我有一个deitalizer,date_time_formats.rb它有:

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

另外在我的datepicker jscript我有正确的格式,我想显示:

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

我已经尝试过这样的事情:

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

但是我得到一个HashWithIndifferentAccess错误。



如何在params哈希中重新格式化日期,然后再分配给该模型?原因是如果日期无效,似乎被拒绝(例如,2013年4月4日是罚款,但2013年4月20日不是因为没有第20个月)。我是一个很大的时间轨道新手,所以也许我错了,但这似乎是如何工作。谢谢!

解决方案

尝试位于这里的 american_date gem:https://github.com/jeremyevans/ruby-american_date


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!

解决方案

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

这篇关于rails在保存到mysql DB之前更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆