ruby DateTime.strftime在日期中显示错误的小时

时间:2011-02-03 20:49:18

标签: ruby-on-rails ruby datetime

我的模型中有以下代码

  def formatted_startdatetime
    unless startdatetime.nil?
      startdatetime.strftime('%d.%m.%Y %H:%M Uhr')
    end
  end

  def formatted_startdatetime=(date_str)
    self.startdatetime = DateTime.strptime(date_str,'%d.%m.%Y %H:%M') unless date_str.blank?
  end

formatted_startdatetime是原始字段startdatetime的attr_accessor。

在视图中,我使用Jquery datetime插件来选择日期时间值。

在数据库中,示例记录的值如下所示。它与视图中显示的内容相同。

  

| 5 | Letzter Kontakt | 2011-02-03   09:00:00 | 2011-02-04 17:00:00 |
  | 19 | NULL |
  NULL | NULL | 2011-02-03   15:14:52 | 2011-02-03 15:14:52 | ddkk   | 1 |

这是一个mysql表,startdatetime是2011-02-03 09:00:00。

但是当我用

在视图上显示它时
  <b>Von:</b>
  <%= @activity.formatted_startdatetime unless @activity.startdatetime.blank? %><br/>

我认为:

  

Von:03.02.2011 10:00 Uhr

为什么实际时间增加1小时? 我怎样才能解决这个问题,并在我存储的同时获得相同的时间?

3 个答案:

答案 0 :(得分:1)

我怀疑您的数据库将日期存储为UTC + 0,而您可能处于UTC + 1国家/地区,因此它们会在阅读时转换回来。

答案 1 :(得分:0)

看起来时间是由rails转换的。

这是config / environment.rb中的时区配置,其中包含以下行

config.time_zone = 'Berlin'

当我在控制台中关注时,我会得到存储在数据库中的时间

@activity.startdatetime_before_type_cast

现在我有两个选择

  1. 要将时区更改为UTC,因为我在时区Europe / Berlin

  2. 使用@ activity.startdatetime_before_type_cast

    打印日期
  3. 哪个选项最好?

答案 2 :(得分:0)

出于某种原因,我只在我的测试中遇到了这个问题。我通过在我创建的日期明确指定UTC偏移来修复它:

@date = Time.new(2012, 12, 27, 20, 15, 0, "+00:00")
visit '/mypage'
expect(page).to have_content @date.strftime '%F %R'