Rails 3: setting the timezone to the current users timezone

前端 未结 3 1574
花落未央
花落未央 2020-12-03 00:00

I put this in Application Controller:

before_filter :set_timezone 

def set_timezone  
Time.zone = current_user.time_zone 
end  

But I alwa

相关标签:
3条回答
  • 2020-12-03 00:34

    Further to Jesse's answer, I should add that you can generally avoid adding a new column in db and just create a custom method in user model and make use of cookie to get the user's timezone:

    in client-side (js):

    function set_time_zone_offset() {
        var current_time = new Date();
        $.cookie('time_zone', current_time.getTimezoneOffset());
    }
    


    in Application Controller:

    before_filter :set_timezone 
    
    def set_timezone  
     min = request.cookies["time_zone"].to_i
     Time.zone = ActiveSupport::TimeZone[-min.minutes]
    end 
    
    0 讨论(0)
  • 2020-12-03 00:38

    Max -- the ryandaigle.com article you mentioned links to this writeup where you need to create a migration to add "time_zone" as an attribute to the user

    (this is from the article, in rails 2.x syntax)

    $ script/generate scaffold User name:string time_zone:string
    $ rake db:migrate
    

    later

    <%= f.time_zone_select :time_zone, TimeZone.us_zones %>
    

    That's why your .time_zone is returning a method_missing -- you haven't stored the time_zone on the user yet.

    0 讨论(0)
  • 2020-12-03 00:56
    function set_time_zone_offset() {
      var current_time = new Date();
      $.cookie('time_zone', current_time.getTimezoneOffset());
    }
    

    This is not correct, because time offset is not constant, it depends on daylight saving time periods. Rails expects the standard time offset when calling ActiveSupport::TimeZone[-min.minutes].

    ex: in France at date 09/03/2013 10:50:12 +02:00, your javascript will return -120 as offset where ActiveSupport will need -60 to resolve France timezone.

    Then you need to check if this is a daylight saving time period in JS then if this is the case you will have to substract one hour to the offset to get the right value used by Rails.

    0 讨论(0)
提交回复
热议问题