Convert Time from one time zone to another in Rails

前端 未结 5 723
粉色の甜心
粉色の甜心 2020-11-29 17:25

My created_at timestamps are stored in UTC:

>> Annotation.last.created_at
=> Sat, 29 Aug 2009 23:30:09 UTC +00:00

How

相关标签:
5条回答
  • 2020-11-29 18:02

    Although this is an old question, it's worth mentioning something. In a previous reply it's suggested to use a before_filter to set the timezone temporally.

    You should never, ever do that because Time.zone stores the information in the thread, and it will probably leak to the next request handled by that thread.

    Instead you should use an around_filter to make sure that the Time.zone is reset after the request is complete. Something like:

    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
    

    Read more about this here

    0 讨论(0)
  • 2020-11-29 18:06

    Use the in_time_zone method of the DateTime class

    Loading development environment (Rails 2.3.2)
    >> now = DateTime.now.utc
    => Sun, 06 Sep 2009 22:27:45 +0000
    >> now.in_time_zone('Eastern Time (US & Canada)')
    => Sun, 06 Sep 2009 18:27:45 EDT -04:00
    >> quit
    

    So for your particular example

    Annotation.last.created_at.in_time_zone('Eastern Time (US & Canada)')
    
    0 讨论(0)
  • 2020-11-29 18:21

    If you configure your /config/application.rb

    config.time_zone = 'Eastern Time (US & Canada)'
    
    Time.now.in_time_zone
    
    DateTime.now.in_time_zone
    
    0 讨论(0)
  • 2020-11-29 18:22

    If you add this to your /config/application.rb

    config.time_zone = 'Eastern Time (US & Canada)'
    

    Then you can cell

    Annotation.last.created_at.in_time_zone
    

    to get the time in the specified time zone.

    0 讨论(0)
  • 2020-11-29 18:28

    Set your timezone to Eastern Time.

    You can set your default timezone in config/environment.rb

    config.time_zone = "Eastern Time (US & Canada)"
    

    Now all records you pull out will be in that time zone. If you need different time zones, say based on a user timezone you can change it with a before_filter in your controller.

    class ApplicationController < ActionController::Base
    
      before_filter :set_timezone
    
      def set_timezone
        Time.zone = current_user.time_zone
      end
    end
    

    Just make sure you are storing all your times in the database as UTC and everything will be sweet.

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