代码之家  ›  专栏  ›  技术社区  ›  Tony

如何在Rails中将时间转换为用户时区

  •  3
  • Tony  · 技术社区  · 15 年前

    我在Rails中使用我的布局中的这个javascript函数设置本地时区:

    <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 回复  |  直到 12 年前
        1
  •  1
  •   Radek Paviensky    15 年前

    您可以设置当前时区,所有操作都会记住它。它可以在一些非常高的控制器(如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
    

    可能它在第一眼看上去不太好,但它会影响所有视图,因此不需要在那里进行任何转换。

    推荐文章