Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

config.active_record.default_timezone = :local ... Doesn't seem to have any effect

The configuration for active_record.default_timezone does not seem to work as advertised. I expected that after setting:

 config.active_record.default_timezone = :local

(in config/application.rb) that a time retrieved from the db would be converted to the local timezone, i.e. it would show the same offset, e.g. "+0200", as a local time.

config.active_record.default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database... http://guides.rubyonrails.org/configuring.html

2.0.0p247 :016 > user = User.new name: "Tom", email: "[email protected]"
 => #<User id: nil, name: "Tom", email: "[email protected]", created_at: nil, updated_at: nil> 

2.0.0p247 :017 > user.save   
(0.3ms)  SAVEPOINT active_record_1
  SQL (0.8ms)  INSERT INTO "users" ("created_at", "email", "name", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", Sun, 08 Sep 2013 23:38:22 UTC +00:00], ["email", "[email protected]"], ["name", "Tom"], ["updated_at", Sun, 08 Sep 2013 23:38:22 UTC +00:00]]
   (0.7ms)  RELEASE SAVEPOINT active_record_1
 => true 

2.0.0p247 :018 > puts user.created_at
2013-09-08 23:38:22 UTC  <----------+  WHY IS THIS THE SAME TIME AS IN THE DB...
 => nil                             |             
                                    |
2.0.0p247 :019 > Time.now           |
=> 2013-09-08 17:38:36 +0200 <------+  ...WHEN THE LOCAL OFFSET IS +0200???

2.0.0p247 :020 > Rails.application.config.active_record.default_timezone
 => :local 

2.0.0p247 :021 > 
2.0.0p247 :022 >   Rails.application.config
 => #<Rails::Application::Configuration:0x00000100af1508 @root=#<Pathname:/Users/7stud/rails_projects/test_postgres>, @generators=#<Rails::Configuration::Generators:0x00000100ff3128 @aliases={}, @options={:rails=>{:orm=>:active_record, :test_framework=>:rspec, :integration_tool=>:rspec, :stylesheet_engine=>:scss, :javascript_engine=>:coffee, :scaffold_controller=>:jbuilder_scaffold_controller, :json_template_engine=>:jbuilder}, :active_record=>{:migration=>true, :timestamps=>true}, :test_unit=>{:fixture=>true, :fixture_replacement=>nil}}, @fallbacks={}, @templates=[], @colorize_logging=true, @hidden_namespaces=["sass"]>, @encoding="utf-8", @allow_concurrency=nil, @consider_all_requests_local=true, @filter_parameters=[:password], @filter_redirect=[], @helpers_paths=["/Users/7stud/rails_projects/test_postgres/app/helpers"], @serve_static_assets=true, @static_cache_control=nil, @force_ssl=false, @ssl_options={}, @session_store=:cookie_store, @session_options={:key=>"_test_postgres_session", :cookie_only=>true}, @time_zone="UTC", @beginning_of_week=:monday, @log_level=:debug, @middleware=#<ActionDispatch::MiddlewareStack:0x00000100fa5158 @middlewares=[ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x00000102a2e6c8>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag]>, @cache_store=[:file_store, "/Users/7stud/rails_projects/test_postgres/tmp/cache/"], @railties_order=[:all], @relative_url_root=nil, @reload_classes_only_on_change=true, @file_watcher=ActiveSupport::FileUpdateChecker, @exceptions_app=nil, @autoflush_log=true, @log_formatter=#<ActiveSupport::Logger::SimpleFormatter:0x00000100af8c18 @datetime_format=nil>, @eager_load=false, @secret_token=nil, @secret_key_base="123f640f8d665d9a20bc49ae045b1a0edd41972db82091ec8bd3ff0836d805698fbe70ca75d2a78c3cd088774412b67f789d74b7a2422ad30acc589487f49ce7", @assets={:enabled=>true, :paths=>[], :precompile=>[#<Proc:0x00000100b02970@/Users/7stud/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application/configuration.rb:54>, /(?:\/|\\|\A)application\.(css|js)$/], :prefix=>"/assets", :version=>"1.0", :debug=>false, :compile=>true, :digest=>false, :cache_store=>[:file_store, "/Users/7stud/rails_projects/test_postgres/tmp/cache/assets/development/"], :js_compressor=>nil, :css_compressor=>nil, :initialize_on_precompile=>true, :logger=>nil}, @paths=#<Rails::Paths::Root:0x00000100b1b6a0 @current=nil, @path=#<Pathname:/Users/7stud/rails_projects/test_postgres>, @root={"app"=>#<Rails::Paths::Path:0x00000100b1b2e0 @paths=["app"], @current="app", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*", @autoload_once=false, @eager_load=true, @autoload=false, @load_path=false>, "app/assets"=>#<Rails::Paths::Path:0x00000100b1aef8 @paths=["app/assets"], @current="app/assets", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*", @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "app/controllers"=>#<Rails::Paths::Path:0x00000100b1ac50 @paths=["app/controllers"], @current="app/controllers", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=true, @autoload=false, @load_path=false>, "app/helpers"=>#<Rails::Paths::Path:0x00000100b1a840 @paths=["app/helpers"], @current="app/helpers", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=true, @autoload=false, @load_path=false>, "app/models"=>#<Rails::Paths::Path:0x00000100b1a110 @paths=["app/models"], @current="app/models", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=true, @autoload=false, @load_path=false>, "app/mailers"=>#<Rails::Paths::Path:0x00000100b19da0 @paths=["app/mailers"], @current="app/mailers", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=true, @autoload=false, @load_path=false>, "app/views"=>#<Rails::Paths::Path:0x00000100b19940 @paths=["app/views"], @current="app/views", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "app/controllers/concerns"=>#<Rails::Paths::Path:0x00000100b193a0 @paths=["app/controllers/concerns"], @current="app/controllers/concerns", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=true, @autoload=false, @load_path=false>, "app/models/concerns"=>#<Rails::Paths::Path:0x00000100b19058 @paths=["app/models/concerns"], @current="app/models/concerns", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=true, @autoload=false, @load_path=false>, "lib"=>#<Rails::Paths::Path:0x00000100b18978 @paths=["lib"], @current="lib", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=true>, "lib/assets"=>#<Rails::Paths::Path:0x00000100b181a8 @paths=["lib/assets"], @current="lib/assets", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*", @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "lib/tasks"=>#<Rails::Paths::Path:0x00000100b238a0 @paths=["lib/tasks"], @current="lib/tasks", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="**/*.rake", @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "config"=>#<Rails::Paths::Path:0x00000100b22f90 @paths=["config"], @current="config", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "config/environments"=>#<Rails::Paths::Path:0x00000100b22090 @paths=["config/environments"], @current="config/environments", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="development.rb", @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "config/initializers"=>#<Rails::Paths::Path:0x00000100b21bb8 @paths=["config/initializers"], @current="config/initializers", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="**/*.rb", @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "config/locales"=>#<Rails::Paths::Path:0x00000100b212a8 @paths=["config/locales"], @current="config/locales", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*.{rb,yml}", @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "config/routes.rb"=>#<Rails::Paths::Path:0x00000100b20d58 @paths=["config/routes.rb"], @current="config/routes.rb", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "db"=>#<Rails::Paths::Path:0x00000100b20858 @paths=["db"], @current="db", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "db/migrate"=>#<Rails::Paths::Path:0x00000100b20510 @paths=["db/migrate"], @current="db/migrate", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "db/seeds.rb"=>#<Rails::Paths::Path:0x00000100b20088 @paths=["db/seeds.rb"], @current="db/seeds.rb", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "vendor"=>#<Rails::Paths::Path:0x00000100b2bf78 @paths=["vendor"], @current="vendor", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=true>, "vendor/assets"=>#<Rails::Paths::Path:0x00000100b2b8e8 @paths=["vendor/assets"], @current="vendor/assets", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*", @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "config/database"=>#<Rails::Paths::Path:0x00000100b2b320 @paths=["config/database.yml"], @current="config/database", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "config/environment"=>#<Rails::Paths::Path:0x00000100b2add0 @paths=["config/environment.rb"], @current="config/environment", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "lib/templates"=>#<Rails::Paths::Path:0x00000100b2a1c8 @paths=["lib/templates"], @current="lib/templates", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "log"=>#<Rails::Paths::Path:0x00000100b29f70 @paths=["log/development.log"], @current="log", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "public"=>#<Rails::Paths::Path:0x00000100b299a8 @paths=["public"], @current="public", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "public/javascripts"=>#<Rails::Paths::Path:0x00000100b29390 @paths=["public/javascripts"], @current="public/javascripts", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "public/stylesheets"=>#<Rails::Paths::Path:0x00000100b28af8 @paths=["public/stylesheets"], @current="public/stylesheets", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>, "tmp"=>#<Rails::Paths::Path:0x00000100b28418 @paths=["tmp"], @current="tmp", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil, @autoload_once=false, @eager_load=false, @autoload=false, @load_path=false>}>, @autoload_paths=[], @eager_load_paths=["/Users/7stud/rails_projects/test_postgres/app/assets", "/Users/7stud/rails_projects/test_postgres/app/controllers", "/Users/7stud/rails_projects/test_postgres/app/helpers", "/Users/7stud/rails_projects/test_postgres/app/mailers", "/Users/7stud/rails_projects/test_postgres/app/models", "/Users/7stud/rails_projects/test_postgres/app/controllers/concerns", "/Users/7stud/rails_projects/test_postgres/app/models/concerns"], @autoload_once_paths=[], @cache_classes=false> 

I also got the same results in my rails app when I displayed the created_at time in a view.

config/application.rb:

require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)

module TestPostgres
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Athens'
    config.active_record.default_timezone = :local


    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de
  end
end
like image 674
7stud Avatar asked Sep 08 '13 23:09

7stud


2 Answers

In order for config.active_record.default_timezone = :local to return a localized time, you need to explicitly declare a default timezone:

# config/application.rb
config.time_zone = 'Singapore'

Subsequently, Rails DateTime objects will be returned from ActiveRecord in localized time:

User.last.created_at
#=> Mon, 09 Sep 2013 09:09:43 SGT +08:00 

Time.now
#=> 2013-09-09 09:11:48 +08:00 
like image 54
zeantsoi Avatar answered Nov 14 '22 11:11

zeantsoi


Be careful here. config.time_zone = "Kuala Lumpur" sets the time zone at the application level.

config.active_record.default_timezone = :local causes records from ActiveRecord to return something like 2000-01-01 00:00:00 +0800

config.active_record.default_timezone = :utc (default) causes records from ActiveRecord to return something like 2000-01-01 00:00:00 UTC for the exact same instance as the above.

I think it is recommended that :local is not used because values written to the DB should be read as UTC. Setting :local would read datetime/time values from the DB as a particular timezone.

Note that Time.now is system level time, since it is a Ruby method. config.time_zone has no bearing on the value returned by Time.now. In the answer above, the user's computer happened to share the same time zone as the application.

More reading: http://danilenko.org/2012/7/6/rails_timezones/

like image 23
Jonathan Lin Avatar answered Nov 14 '22 12:11

Jonathan Lin