Timezone with rails 3

后端 未结 4 451
北恋
北恋 2020-12-02 09:32

I have pretty common issue but for some reason i have tried all the suggestions on the web and none seem to work.

I have set the Timezone in config to \'EST\'

相关标签:
4条回答
  • 2020-12-02 09:53

    Check that your ActiveRecord::Base.time_zone_aware_attributes is true.

    0 讨论(0)
  • 2020-12-02 10:06

    If you want to set a different time zone for different users of your app, make sure you use an around_filter as opposed to a before filter to change Time.zone. Something to do with how Time.zone leaks over to other threads and thus other users may inheret a time zone that they shouldn't. From this blog post: http://ilikestuffblog.com/2011/02/03/how-to-set-a-time-zone-for-each-request-in-rails/

    in application_controller.rb:

    around_filter :set_time_zone
    
    private
    
    def set_time_zone
      old_time_zone = Time.zone
      Time.zone = current_user.time_zone if logged_in?
      yield
    ensure
      Time.zone = old_time_zone
    end
    

    I also found it helpful to use the time_zone_select form helper method when allowing users to change their time zone. If you called your field :time_zone, you would use it like:

    f.time_zone_select(:time_zone)
    

    And lastly, this looks pretty awesome. Auto detect and set time zone via javascript. Here's the rails gem to add to the asset pipeline: https://github.com/scottwater/detect_timezone_rails and accompanying blog post: http://www.scottw.com/automated-timezone-detection

    0 讨论(0)
  • 2020-12-02 10:07

    Try in_time_zone. For example

    >> Time.now
    => Sun Dec 05 21:34:45 -0500 2010
    >> Time.zone
    => #<ActiveSupport::TimeZone:0x1033d97b8 @name="Pacific Time (US & Canada)", @tzinfo=#<TZInfo::DataTimezone: America/Los_Angeles>, @utc_offset=-28800, @current_period=nil>
    >> Time.now.in_time_zone
    => Sun, 05 Dec 2010 18:34:54 PST -08:00
    

    In your case, you want Order.first.placed_at.in_time_zone.

    0 讨论(0)
  • 2020-12-02 10:16

    I think what you're describing is this bug - https://github.com/rails/rails/issues/6816

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