2013-11-27 19 views
0

所以...我試圖在地圖上創建東西。有一個日期和時間與事物相關,但它目前節省1:1。所以,如果我保存一些東西並給它一個2013-11-28 @ 12:00 pm的日期,那麼它會在該特定時間保存到數據庫中。它應該是保存UTC ...所以2013-11-28 @ 18:00 pm在我的情況。使用Rails在時區內創建模型

我有一個時區的around_filter ...

class ApplicationController < ActionController::Base 
    around_filter :user_time_zone, if: :current_user 

private 

    def user_time_zone(&block) 
    Time.use_zone(current_user.location, &block) 
    end 
end 

因此,一旦事情被保存...這是正確的時間劃,並顯示爲2013-11-28 @ 04:00 am

我想在設置時間時使用Time.use_zone函數,但這也不起作用。我使用谷歌獲得的,其中一點是地圖上的時區...

JSON.load(open("https://maps.googleapis.com/maps/api/timezone/json?location=#{params[:lat]},#{params[:lng]}&timestamp=1331161200&sensor=false"))["timeZoneId"] 

讓我適當的時區...但我似乎無法在保存過程中應用它。它可能與模型有關?我有日期和時間不同的領域......我在模型結合他們:

before_create :convert_to_start 

# Start 
def startDate 
    start.strftime("%d/%m/%Y") if start.present? 
end 
def startDate=(date) 
    # Change back to datetime friendly format 
    @startDate = Date.parse(date).strftime("%Y-%m-%d") 
end 
def startTime 
    start.strftime("%I:%M%p") if start.present? 
end 
def startTime=(time) 
    # Change back to datetime friendly format 
    @startTime = Time.parse(time).strftime("%H:%M:%S") 
end 

def convert_to_start 
    self.start = DateTime.parse("#{@startDate} #{@startTime}") 
end 

我想我需要傳遞,我從谷歌得到的模型這些方法的時區,但我似乎無法弄清楚如何與他們互動。

+0

慢性寶石就是答案......我試圖堅持使用本土軌的東西,但慢性實在是太真棒。 'Chronic.time_class = ActiveSupport :: TimeZone.create(#google獲取的時區)',然後在模型中,所有這些解析變爲'Chronic.parse'。他們全部... – Dudo

回答

0

慢性寶石解決了這個問題。

tz = JSON.load(open("https://maps.googleapis.com/maps/api/timezone/json?location=#{params[:event][:lat]},#{params[:event][:lng]}&timestamp=1331161200&sensor=false"))["timeZoneId"] 
Chronic.time_class = ActiveSupport::TimeZone.create(tz) 

然後在模型......所有這些解析成爲

def startDate=(date) 
    # Change back to datetime friendly format 
    @startDate = Chronic.parse(date).strftime("%Y-%m-%d") 
end 
相關問題