簡體   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