代码之家  ›  专栏  ›  技术社区  ›  Sniggerfardimungus

RubyonRails和ActiveRecord独立脚本在以下数据库值上存在分歧:时间戳

  •  2
  • Sniggerfardimungus  · 技术社区  · 17 年前

    今天早些时候我发布了一个问题,当时我还没有集中精力解决这个问题。我会在这里更简洁。

    我在Windows上用MySQL运行Ror2.1.2。SQL server的本机时区为UTC。我的本地时区是太平洋(-0800)

    我有一个带有:timestamp类型列的模型,我可以使用该列执行以下操作:

    record = Record.find(:first)
    record.the_time = Time.now()
    

    这就是麻烦的开始。如果我在视图中显示时间:

    <%= h record.the_time %>
    

    …然后返回正确的时间,以UTC格式显示。如果我在当地时间16:40:00写入数据库,数据库显示00:40:00。

    但是,如果我运行的是独立脚本:

    record = Record.find(:first)
    puts record.the_time
    

    …然后返回存储在数据库中的UTC时间(00:40:00),但使用本地时区:

    Wed Nov 26 00:40:00 (-0800) 2008
    

    有什么想法吗?

    4 回复  |  直到 17 年前
        1
  •  1
  •   mrflip    17 年前

    config/environment.rb中有一个设置,用于设置时区。这可能与脚本中的设置不同:

    # Make Time.zone default to the specified zone, and make Active Record store time values
    # in the database in UTC, and return them converted to the specified local zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time.
    config.time_zone = 'UTC'
    

    您还可以尝试显式指定TZ和格式:

    require 'active_support/core_ext/date/conversions'
    record.the_time.utc.to_s(:db) 
    

    (或者,如果您在独立脚本中未使用活动的_支持,则作弊并从中获取代码片段)

        2
  •  1
  •   Daniel Lucraft    17 年前

    试着要求 active_support

        3
  •  0
  •   allesklar    17 年前

    我有一个类似的问题,当我这样做的时候,它得到了修复。

    您还提到了一个独立脚本,但是为了获得Rails的时区特性,代码需要在Rails中运行。

        4
  •  0
  •   Sniggerfardimungus    17 年前

    最后,通过将时间存储为整数(Time.now().to_i())并将它们转换回需要显示它们的时间(Time.at(the_Time)_数据库_返回给_me),实现这一点要容易得多。这几乎不是最好的解决方案,但它是唯一有效的解决方案。

    推荐文章