【问题标题】:querying postres with rails and time zones使用 rails 和 time zone 查询 postgres
【发布时间】:2014-07-10 21:50:31
【问题描述】:

我正在查询这样的结果:

@logs.where("extract(dow from created_at at time zone ?) = ?", "America/New_York", day_of_week)

但它不起作用。 (我也在那里尝试过“Time.zone.tzinfo.identifier”,但在这里使用结果进行测试和澄清。)例如,有人可能在东部时间 10:30 发帖,但由于它存储在 UTC,它不会出现在包含它的查询中。

我开始了一个新问题,因为我从这里得到了这个答案,即使它有一个公认的答案,它显然对我不起作用: handling rails + postgres and timezones

这种方法有什么问题吗?还有其他当前或更好的方法吗?

更新信息:

created_at 存储为日期时间。我的时区设置仍然是 UTC,但我正在尝试获取带有“America/New_York”区域的帖子,应该仍然有效。不起作用,我的意思是我会查询 15 号,一些帖子会返回,但是由于 UTC 差异,一些在 15 号当天晚些时候发布的帖子仍然会在 16 号返回。包含它的查询列在代码块上方。我正在尝试从时区“America/New_York”的 created_at 获取 dow。

【问题讨论】:

  • created_at 的确切数据类型?你的时区设置? it's not working - 如何 到底是什么? “包含它的查询”的确切 SQL? This related answer may be of help.

标签: ruby-on-rails postgresql timezone


【解决方案1】:
@logs = @logs.where("extract(day from (created_at at time zone 'Etc/UTC') at time zone ?) = ?", Time.zone.tzinfo.identifier, params[:date].to_f)

终于明白了!主要来自此链接,但有一些小的调整:

PostgreSQL: selecting rows that occur on a certain day of the week, in a specific time zone

【讨论】:

    【解决方案2】:

    这是我写的一篇关于 Rails 和时区的博文,您可能会觉得它有帮助? http://jessehouse.com/blog/2013/11/15/working-with-timezones-and-ruby-on-rails/

    尝试像这样运行您的查询

    Time.use_zone("Eastern Time (US & Canada)") do 
      start_at = (Date.current - 1.day).beginning_of_day
      end_at = start_at.end_of_day
      @logs_from_yesterday = Log.where("created_at BETWEEN ? AND ?", start_at, end_at)
    end
    

    Rails 会自动将日期时间过滤器偏移到 use_zone 块中指定的时区,并且 Date.current 可以识别时区(Time.zone.now.to_date 的别名)

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 2011-03-14
      • 2021-11-30
      • 2012-04-04
      • 2018-04-17
      • 2019-12-31
      • 2017-01-05
      • 2015-03-12
      相关资源
      最近更新 更多