2012-04-19 52 views
0

我已經看過幾個StackOverflow的問題,但他們都沒有看到破解的情況。我該如何保持時間,但改變時區?

我的例如時間是:

2012-04-19 08:42:00 +0200 

這就是通過表單inputed。如何保持相同的時間,但只是改變了區域

Wed, 18 Apr 2012 23:42:00 PDT -07:00 

:但是,一切都相對於其所在的時區顯示是因爲電腦工作在UTC,它被保存在此時間後出來的。 ?

回答

1

我有同樣的要求。請檢查thisthis link

或者

"2012-04-19 08:42:00 +0200".to_time.strftime("%c").to_datetime 
2

我覺得方法Time.use_zone可能會幫助你。在應用程序中,我正在工作,我們希望根據當前用戶的時區對時間進行解釋。我們User類被賦予了time_zone屬性,它僅僅是一個有效的ActiveSupport::TimeZone字符串,我們創建了一個around_filter如下:

class ApplicationController < ActionController::Base 

    around_filter :activate_user_time_zone 

    def activate_user_time_zone 
    return yield unless current_user # nothing to do if no user logged in 
    return yield unless current_user.time_zone && ActiveSupport::TimeZone[current_user.time_zone] # nothing to do if no user zone or zone is incorrect 
    Time.use_zone(ActiveSupport::TimeZone[current_user.time_zone]) do 
     yield 
    end 
end 

end 

基本上,這將在控制器動作執行的代碼,就好像是在當前用戶的時區。

相關問題