2010-09-29 67 views
3

我设置在轨道上的本地时区,在我的布局这个JavaScript函数:如何将时间转换为用户的时区中的Rails

<script type="text/javascript" charset="utf-8"> 
    <% unless session[:timezone_offset] %> 
     $.ajax({ 
       url: '/main/timezone', 
       type: 'GET', 
       data: { offset: (new Date()).getTimezoneOffset() } 
     }); 
    <% end %> 
</script> 

如果是这种接收功能:

# GET /main/timezone              AJAX 
    #---------------------------------------------------------------------------- 
    def timezone 
    # 
    # (new Date()).getTimezoneOffset() in JavaScript returns (UTC - localtime) in 
    # minutes, while ActiveSupport::TimeZone expects (localtime - UTC) in seconds. 
    # 
    if params[:offset] 
     session[:timezone_offset] = params[:offset].to_i * -60 
     ActiveSupport::TimeZone[session[:timezone_offset]] 
    end 
    render :nothing => true 
    end 

然后,我已经在我的会话偏移,所以我做这样的事情来显示时间:

<%= (@product.created_at + session[:timezone_offset]).strftime("%m/%d/%Y %I:%M%p") + " #{ActiveSupport::TimeZone[session[:timezone_offset]]}" %> 

是所有这在Rails 3中是非常必要的吗?我认为前两个代码块可能是,但第三个代码块可能是,但第三个似乎有点过分...

回答

1

您可以设置当前时区,它将被记住的所有操作。它可以在一些非常高的控制器的before_filter中完成,比如AppController。例如

class ApplicationController < ActionController::Base 
    before_filter :set_zone_from_session 

    private 

    def set_zone_from_session 
    # set TZ only if stored in session. If not set then the default from config is to be used 
    # (it should be set to UTC) 
    Time.zone = ActiveSupport::TimeZone[session[:timezone_offset]] if session[:timezone_offset] 
    end 

end 

也许它不看的第一眼更好 - 但它会影响所有视图,以便无需任何转换那里。

+0

只有这个问题才会在那个时区保存,所以现在我的数据库将有时间保存在不同的时区。如果它能够跟踪时区,那么这可能并不糟糕......您怎么看?这是如何正常完成的?谢谢! – Tony 2010-09-30 04:22:08

+0

它不应该保存时区 - 在正常情况下。例如,Postgres的迁移创建没有区域信息的时间列。相同的Sqlite。所以应该没有关于存储时区的信息。我有一些疯狂的想法来列出简单的例子,使用tzones就是其中之一。但不是现在,因为我必须为生活做些工作:-) – 2010-09-30 07:51:25

+0

当我再次阅读时,我有一种感觉,我不够清楚 - 时间始终以UTC存储,无论您的Time.zone设置如何。 – 2010-09-30 07:55:19

相关问题