【问题标题】:How to convert time to date in the local timezone during query如何在查询期间将本地时区的时间转换为日期
【发布时间】:2012-01-28 23:19:45
【问题描述】:

我们有一个非常简单的付款模型,其中包含我们必须在日期范围内搜索的默认“created_at”日期时间字段,所以我这样做了:

>> Payment.all(:conditions => 
              ["Date(payments.created_at) >= ? and 
                Date(payments.created_at) <= ?", start_date, end_date])

我遇到了日期函数的问题。例如

>> Payment.find(2577).created_at
=> Thu, 15 Dec 2011 18:15:00 UTC +00:00

但是

>> Payment.find(2577).created_at.localtime
=> Fri Dec 16 01:15:00 +0700 2011

因此,当我们在 12 月 16 日搜索付款时,我们没有得到任何结果,因为 Date(payments.created_at) 将 UTC 时间转换为日期,然后转换为 12 月 15 日。

是否可以修改 Date(payments.created_at) 以便它搜索本地时区的日期?我们使用的是 Rails 2.3.5 和 postgresql。

【问题讨论】:

    标签: sql ruby-on-rails postgresql activerecord timezone


    【解决方案1】:

    终于搞定了!不是很漂亮(我希望有一个更清洁的解决方案),但这很有效:

    >> Payment.all(:conditions => 
                  ["Date((payments.created_at at time zone 'UTC') 
                    at time zone :timezone) >= :start_date and 
                    Date((payments.created_at at time zone 'UTC') 
                    at time zone :timezone) <= :end_date",
                   :start_date => start_date, :end_date => end_date, 
                   :timezone => 'Asia/Katmandu'])
    

    虽然不是很喜欢这样做:

    Date((payments.created_at at time zone 'UTC') at time zone 'Asia/Katmandu')
    

    为什么 postgresql 不允许你这样做?

    Date(payments.created_at at 'Asia/Katmandu')
    

    【讨论】:

      【解决方案2】:

      你能在你的 start_date 和 end_date 上运行 .localtime 吗?比如:

      Payment.all(:conditions => 
        ["Date(payments.created_at) >= ? and 
          Date(payments.created_at) <= ?", start_date.localtime, end_date.localtime])
      

      您还可以在 config/environment.rb 文件中设置您的本地时区:

      config.time_zone = 'UTC'
      

      【讨论】:

        猜你喜欢
        • 2021-05-02
        • 2019-01-14
        • 1970-01-01
        • 2012-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 2013-02-14
        相关资源
        最近更新 更多