Convert Time from one time zone to another in Rails

前端 未结 5 753
粉色の甜心
粉色の甜心 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: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.

提交回复
热议问题