How to convert time to user timezone in Rails

I set the local time zone in Rails using this JavaScript function in my layout:

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

where is the receiving function:

# 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

And then I have an offset in my session, so I'm doing something like this to show the time:

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

Is all this really necessary in Rails 3? I think the first two blocks of code may be, but the third seems a bit excessive ...

+3
source share
1 answer

You can set the current time zone and it will be remembered for all operations. This can be done in the before_filter file of some very high controller, for example AppController. for instance

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

, , , - .

+1

Source: https://habr.com/ru/post/1767091/


All Articles