【问题标题】:Custom timestamp field cannot be changed in rails无法在 Rails 中更改自定义时间戳字段
【发布时间】:2013-02-03 21:07:44
【问题描述】:

我最近在我的数据库中添加了一个名为 created_at_user_time 的列(最初没有值),它应该包含一个时区转换的 created_at 时间戳。我制作了一个快速脚本,该脚本应该进行转换并将其保存在新列中。然而,在我完成后,我注意到原来的时间戳刚刚被复制到新的时间戳中。我决定在 Rails 控制台中进行调查并得到以下信息。

1.9.3p194 :002 > user.time_zone
=> "Central Time (US & Canada)"
1.9.3p194 :003 > test = user.orders.first
1.9.3p194 :004 > test.created_at
=> Wed, 02 Jan 2013 02:02:54 UTC +00:00 
1.9.3p194 :006 > newstamp = test.created_at.in_time_zone("#{user.time_zone}")
=> Tue, 01 Jan 2013 20:02:54 CST -06:00 
1.9.3p194 :008 > test.created_at_user_time = newstamp
=> Tue, 01 Jan 2013 20:02:54 CST -06:00 

#ok, now lets save and check it

1.9.3p194 :009 > test.save
(0.4ms)  begin transaction
(0.1ms)  commit transaction
=> true 


1.9.3p194 :010 > test = user.orders.first
1.9.3p194 :011 > test.created_at_user_time
=> Wed, 02 Jan 2013 02:02:54 UTC +00:00 

有人对如何正确执行此操作有任何想法吗?

【问题讨论】:

    标签: ruby-on-rails sqlite rails-activerecord


    【解决方案1】:

    我会说这将返回相同的时间但具有不同的时区,但最后它直到相同的时间戳:

    newstamp = test.created_at.in_time_zone
    

    【讨论】:

    • 你我应该怎么做?
    • 你想做什么?
    • 将转换后的时间戳保存到数据库中
    • 但您尝试保存的日期完全相同... 2013 年 1 月 2 日星期三 02:02:54 UTC +00:00 === 2013 年 1 月 1 日星期二 20:02: 54 CST -06:00。这只是一个演示的问题......
    • 我需要将它们保存在该状态,以便以后可以按日期正确分组stackoverflow.com/questions/14412360/…。如果日期恰好不同,它将无法正常工作。
    【解决方案2】:

    正如 MiGro 指出的那样,仅使用 .in_time_zone 方法只会更改时间戳在文本中的显示方式,实际上并不会更改值。为了更改值,我从转换后的时间值中获取偏移量并将其添加到原始时间,从而使我能够按正确的日期对订单进行分组(请参阅我之前的问题 Modify created_at in query before grouping by date)。

     test_order = user.order.first 
     orig_time = test_order.created_at
     conv_time = orig_time.in_time_zone(user.time_zone)
     offset = conv_time.utc_offset
     order.created_at_in_user_time = orig_time + offset
    

    【讨论】:

      猜你喜欢
      • 2015-02-20
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多