如何在查询期间将时间转换为本地时区中的日期 [英] How to convert time to date in the local timezone during query

查看:89
本文介绍了如何在查询期间将时间转换为本地时区中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个非常简单的付款模型,带有默认的 created_at日期时间字段,我们必须在日期范围内进行搜索,所以我这样做:

We have a very simple payments model with the default "created_at" datetime field that we have to search in a date range so I did this:

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

日期功能出现问题。例如,

I'm having an issue with the Date function. For example

>> 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日,因此没有任何结果。

So when we search for payments on Dec 16 we don't get any results since Date(payments.created_at) converts the UTC time to date which gets converted to Dec 15.

是否可以修改Date(付款)。 created_at),以便改为搜索本地时区的日期?我们正在使用Rails 2.3.5和postgresql。

Is it possible to modify Date(payments.created_at) so that it searches for dates the local timezone instead? We are using Rails 2.3.5 and postgresql.

推荐答案

终于使它起作用了!不太漂亮(我希望有一个更干净的解决方案),但是可以用:

Finally got it to work! Not very pretty (and I'm hoping there's a cleaner solution) but this worked:

>> 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'])

虽然不是很喜欢这样做:

Not really liking having to do this though:

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

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

How come postgresql doesn't let you just do this?

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

这篇关于如何在查询期间将时间转换为本地时区中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆