问题
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
But
>> Payment.find(2577).created_at.localtime
=> Fri Dec 16 01:15:00 +0700 2011
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.
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.
回答1:
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')
How come postgresql doesn't let you just do this?
Date(payments.created_at at 'Asia/Katmandu')
回答2:
Can you just run .localtime on your start_date and end_date? Something like:
Payment.all(:conditions =>
["Date(payments.created_at) >= ? and
Date(payments.created_at) <= ?", start_date.localtime, end_date.localtime])
You might also be able to set your local timezone in config/environment.rb file:
config.time_zone = 'UTC'
来源:https://stackoverflow.com/questions/8652623/how-to-convert-time-to-date-in-the-local-timezone-during-query