繁体   English   中英

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

[英]How do I convert a time to users time zone in Rails

我在我的布局中使用此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中所有这些都是必需的吗? 我认为前两个代码块可能是,但第三个似乎有点过分...

您可以设置当前时区,并记住所有操作。 它可以在某个非常高的控制器的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

可能它在第一眼看上去并不好看 - 但它会影响所有观点,所以不需要在那里进行任何转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM