【问题标题】:Rails 4 - Date is mix-matching day and month after form submissionRails 4 - 日期是表单提交后的混合日期和月份
【发布时间】:2016-04-09 04:23:53
【问题描述】:

我正在使用 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)

预期输入到 DB:2016/04/09

实际在 locales/en.yml 更改后输入到 DB:2016/09/04

所以这向我展示了更改格式会以某种方式更改日期和月份。提交给数据库的参数是:["tripDate", "2016-09-04"]

但是 rails 日志消息给了我正确的日期输出:Started POST "/reservations" for ::1 at 2016-04-09 09:00:21 -0400

这让我相信这颗宝石可能有问题。

在保存之前,我没有对 tripDate 属性进行任何其他更改。有人可以解释发生了什么以及解决方案是什么吗?

【问题讨论】:

  • 您如何检查创建的记录?数据库中的数据是正确的还是只是显示出来的?
  • @FrederickCheung 我尝试了几种方法,我在本地机器上查看终端中的日志,然后我运行 rails 控制台拉列打印它并查看检索到的数据应用程序。
  • 无论您输入的格式是什么,存储在数据库中的数据都具有相同的格式 - 在 rails 控制台中检查日期是否具有正确的值(如果需要,请使用 strftime 重新格式化)。如果这会产生正确的结果但您的视图没有,那么问题在于视图如何格式化数据,如果数据库中的数据不正确,那么问题就是您的输入。找出它是哪一个并相应地更新您的问题(可以想象,在这种情况下,首先要关注在数据库中获取正确的数据)
  • 将继续检查明天,因为已经很晚了。 @FrederickCheung

标签: ruby-on-rails ruby-on-rails-4 time rubygems rails-i18n


【解决方案1】:

通过关注this SO 帖子解决了我的困境。更具体地说,给出的问题的最后一个解决方案是按照这些思路做一些事情:

def create
 .....
 @person.dob = DateTime.strptime(params[:person][:dob], '%m/%d/%Y').to_date
 .....
 @person.save
 .....
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多