我在查詢時遇到了很多麻煩。我真的不知道如何解釋這一點,但我會嘗試。查詢日期時間範圍,同時考慮到時區
基本上,我們有幾個對象帶有'posted_at'字段,用於在日期時間字段中保存日期和時間以及時區。我需要查詢和獲取這些對象的日期範圍。
以前,我將它轉換爲Date並將它與另一個Date對象進行比較。查詢是這樣的:
Date(posted_at) >= :start_date AND Date(posted_at) <= :end_date
然而,當Postgre它轉換爲日期,就失去了造成不準確的效果在查詢時區信息。
於是,我改變了這個:
if start_date then
start_time = Time.zone.parse("#{start_date.year}-#{start_date.month}-#{start_date.day}")
conditions << "posted_at >= :start"
hash[:start] = start_time
end
if end_date then
end_time = Time.zone.parse("#{end_date.year}-#{end_date.month}-#{end_date.day}").end_of_day
conditions << "posted_at <= :end"
hash[:end] = end_time
end
雖然這讓我準確的結果,它也有可怕的性能,並導致一些超時在我的應用程序。
我找不到任何其他方式來做這個查詢,仍然保持準確的結果。會有人有一些建議或想法?
預先感謝您。
非常感謝Denis,值得了解。 – MarceloJ 2011-05-17 19:47:34