2012-09-21 22 views
2

我的日期方法在Heroku上無法正常工作。我創建了一個用戶,其用戶名爲(GMT-05:00) Eastern Time (US & Canada),並且根據它所具有的date屬性來設想添加產品。所以它假設說Added 1 Product Today,但它就好像它們是在前一天記錄的方法一樣。所以today實際上是昨天,yesterday其實就是後天。如何解決在Heroku上關閉日期方法?

這裏是我的方法:

def self.today 
    where(:date => Date.today) 
    end 

    def self.yesterday 
    where(:date => Date.yesterday) 
    end 

    def self.this_week 
    where(:date => Date.today.beginning_of_week..Date.today.end_of_week) 
    end 

    def self.last_week 
    where(:date => 1.week.ago.beginning_of_week..1.week.ago.end_of_week) 
    end 

    def self.this_month 
    where(:date => Date.today.beginning_of_month..Date.today.end_of_month) 
    end 

    def self.last_month 
    where(:date => 1.month.ago.beginning_of_month..1.month.ago.end_of_month).order('date desc') 
    end 

所以我想它總是-1 day用於在Heroku上的每一個方法,但不是在發展。 Heroku的時區和時間是:

Loading production environment (Rails 3.2.8) 
irb(main):001:0> Time.now 
Time.now 
=> 2012-09-21 02:37:26 +0000 
irb(main):002:0> Time.zone 
Time.zone 
=> (GMT+00:00) UTC 

這是錯誤的我,因爲它是在美國東2012-09-20

我想要的方法適用於每個時區,而不僅僅是Eastern Timezone所以我應該怎麼做呢?我如何讓用戶根據他們的時區查看他們添加的產品?

謝謝。

回答

2

那麼,如果你想全球一個時區,最簡單的方法是heroku config:set TZ到一些合適的價值。這涵蓋了從libc到up的所有內容。

但是,用戶特定的時區意味着您需要在每個請求的上下文內更改時區。 「每個請求」應該立即讓你想到「在控制器中」。

事實證明,Rails(特別是ActionSupport)爲此與Time.zone=進行了規定。它還碰巧的是,這是很常見的zone=文檔包括示例代碼專門爲這樣的場景:

class ApplicationController < ActionController::Base 
    around_filter :set_time_zone 

    def set_time_zone 
    old_time_zone = Time.zone 
    Time.zone = current_user.time_zone if logged_in? 
    yield 
    ensure 
    Time.zone = old_time_zone 
    end 
end 

另外,如果你不能讓用戶從列表中選擇自己的時區,你可以guess based on the time zone offset detected in JavaScript 。這比沒有好。

0

加入這一行到application.rb中config文件夾下

config.active_record.default_timezone = 'GMT + 5.30'

1

你需要前綴的時間點搜索功能與in_time_zone。例如Date.today.beginning_of_week應該是Date.today.in_time_zone(users_tz).beginning_of_week

相關問題