1

我已经阅读了很多关于这个问题的帖子,但似乎没有一个足够清楚地解决它。

基本上我有一个Receipt带有日期时间字段的模型doc_date

当我保存日期时,我将它保存在我的本地区域(里斯本,目前使用 DST:GMT +1)。在数据库中,我有 Utc (gmt) 日期。也就是说,比我现在的时间还不到一小时。

到目前为止,一切都很好。

问题是当我将字段加载到表单时。

<%= form_for(@receipt) do |f| %>
[...]
 <div class="field">
      Date Test </br>
      <%=  @receipt.doc_date %>
    </div>
 <div class="field">
  <%= f.label :doc_date %>
  <%= f.text_field :doc_date %>
 </div>
[...]
<% end %>

如果保存的日期为“2013 年 8 月 1 日 00:00”,则 Doc 日期输入字段中的显示日期为“2013 年 7 月 31 日 23:00”。

另一端的日期测试显示正确

Date Test
2013/08/01 00:00 

在我的 application_controller 我也有

before_filter :set_user_time_zone

  #Sets the user default time zone to the one configured in the db
  def set_user_time_zone

    Time.zone = current_user.time_zone if user_signed_in?
  end

在我的 application.rb 我有config.time_zone = 'Lisbon'

我正在运行 Rails 3.2。

如果我在控制台中运行 Receipt.where(id:18365).first.doc_date ,日期也会返回 1 August 00:00,所以问题似乎在于加载表单......

所以这似乎与Rails跳过表单字段的时区转换有关,或者与我有该字段的jquery datepicker日历这一事实有关......

有什么建议可以在表单字段上显示正确的本地日期时间吗?

4

1 回答 1

2

根据评论:

字段的时区有一个很好的答案:Rails 'config.time_zone' 不适用于加载到 text_field 中的日期时间数据。使固定?


<%= f.text_field :doc_date, value: f.object.doc_date %>
于 2013-09-19T18:13:49.393 回答