【问题标题】:Rails Json response automatically changes timezeone only on some requestsRails Json 响应仅在某些请求上自动更改 timezeone
【发布时间】:2014-07-31 01:08:05
【问题描述】:

我们在 rails 4 中有一个简单的 json API,它使用 jbuilder 返回数据。其中一个字段是日期时间字段“date_of_birth”,json 格式的行为很奇怪。对 API 的相同请求可以随机生成 2 个不同的结果

"date_of_birth":"1989-06-14T20:52:00-07:00"

"date_of_birth":"1989-06-15T03:52:00Z"

如您所见,第一个是本地时间,另一个是 UTC 时区。我们将时区全局设置为“UTC”。

这是 jbuilder 视图中产生输出的行,没什么特别的'

json.array!(@patients) do |patient|
  json.extract! patient, :id, :first_name, :last_name, :gender, :groups_code, :date_of_birth
end

什么可能导致这个问题?

【问题讨论】:

  • 你在你的 development.rb 中尝试过config.time_zone 的配置吗?
  • 我的 config/application.rb 中有 config.time_zone = 'UTC'。这发生在所有环境中。
  • 我也有这个问题。我可以一遍又一遍地触发相同的 API 调用,然后它会以不同的格式返回,没有押韵或原因。

标签: ruby-on-rails timezone jbuilder


【解决方案1】:

Rails 在时间方面做了一些非常聪明的工作,以覆盖具有不同时区和服务器独立托管位置的用户。基本上,时间存储在 UTC 时区的数据库中,并在需要时转换为本地服务器/或用户时区。

在标准 Rails 应用程序中,您有 3 个时区可以相同或不同:数据库时区、默认时区和用户时区。

看看这个很好的article,它说明了一切。然后在导出到 json 时将正确的方法应用于您的 date_of_birth 字段

做事

2.hours.ago # => Fri, 02 Mar 2012 20:04:47 JST +09:00
1.day.from_now # => Fri, 03 Mar 2012 22:04:47 JST +09:00
Date.today.to_time_in_current_zone # => Fri, 02 Mar 2012 22:04:47 JST +09:00
Date.current # => Fri, 02 Mar
Time.zone.parse("2012-03-02 16:05:37") # => Fri, 02 Mar 2012 16:05:37 JST +09:00
Time.zone.now # => Fri, 02 Mar 2012 22:04:47 JST +09:00
Time.current # Same thing but shorter. (Thank you Lukas Sarnacki pointing this out.)
Time.zone.today # If you really can't have a Time or DateTime for some reason
Time.zone.now.utc.iso8601 # When supliyng an API (you can actually skip .zone here, but I find it better to always use it, than miss it when it's needed)
Time.strptime(time_string, '%Y-%m-%dT%H:%M:%S%z').in_time_zone(Time.zone) # If you can't use Time#parse

不要做

Time.now # => Returns system time and ignores your configured time zone.
Time.parse("2012-03-02 16:05:37") # => Will assume time string given is in the system's time zone.
Time.strptime(time_string, '%Y-%m-%dT%H:%M:%S%z') # Same problem as with Time#parse.
Date.today # This could be yesterday or tomorrow depending on the machine's time zone.
Date.today.to_time # => # Still not the configured time zone.

【讨论】:

  • 感谢您提供文章的链接,非常有帮助。但我仍然很困惑,为什么 rails 会为来自同一客户端的 2 个请求返回 2 个不同的响应。
  • 同样的问题!
【解决方案2】:

您可能根据用户时区设置在某处设置了Time.zone = ...

【讨论】:

    【解决方案3】:

    我也遇到过同样的问题,但无法弄清楚它发生的原因。这里的其他答案似乎忽略了返回的时间格式似乎是随机的,对代码/配置没有任何更改。

    我能够通过使用.to_time.iso8601 我的JBuilder 块来“修复”这个问题,这将强制使用1989-06-15T03:52:00Z 格式。

    【讨论】:

      猜你喜欢
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2019-03-31
      相关资源
      最近更新 更多