我正在使用gem 'datetimepicker-rails'
,特别是在我的simple_form
中使用date_picker,如下所示:
<%= f.input :tripDate, :as => :date_picker, label: 'Pick-up Date', placeholder: 'Click icon on right', input_html: {data: {date_options: {showClose: true}}} %>
该字段的输入框以我想要的格式显示了日期的正确输出,但数据库中保存的日期是随着月份和日期的变化而保存的。
文档指出要更改config/locales/en.yml
,所以我将其更改为以下格式:
en:
datepicker:
dformat: '%m/%d/%Y' # display format of the date (this is the default, can be ommited)
pformat: 'MM/DD/YYYY' # picking format of the date (this is the default, can be ommited)
timepicker:
dformat: '%R' # display format of the time (this is the default, can be ommited)
pformat: 'hh:mm A' # picking format of the time (this is the default, can be ommited)
dayViewHeaderFormat: 'MMMM YYYY' # picking format of the time (this is the default, can be ommited)
预计数据库输入:2016/04/09
locale/en.yml更改后数据库的实际输入2016/09/04
因此,这向我表明,改变格式就是在某种程度上改变日期和月份。提交给DB的参数是:["tripDate", "2016-09-04"]
但是rails日志消息给了我正确的日期输出:Started POST "/reservations" for ::1 at 2016-04-09 09:00:21 -0400
这让我相信宝石可能出了问题。
在保存之前,我不会对tripDate属性进行任何其他更改。有人能解释一下发生了什么以及解决方案是什么吗?
通过关注这篇SO帖子,我的困境得到了解决。更具体地说,这个问题的最后一个解决方案是:
def create
.....
@person.dob = DateTime.strptime(params[:person][:dob], '%m/%d/%Y').to_date
.....
@person.save
.....
end