Default TimeZone with ActiveSupport (without Rails) Default TimeZone with ActiveSupport (without Rails) ruby ruby

Default TimeZone with ActiveSupport (without Rails)


in rails it gets set in environment.rb via the rails initializer

Rails::Initializer.run do |config|    config.time_zone = 'Pacific Time (US & Canada)'    # ...

I just did a test and when the config.time_zone is commented out Time.zone will also return nil in the rails project; so I guess there is not a 'default' it just gets set in the initializers

Guessing you already know this will 'work'?

irb -r 'rubygems'ruby-1.8.7-p174 > require 'active_support' ruby-1.8.7-p174 > require 'active_support/time_with_zone'ruby-1.8.7-p174 > Time.zoneruby-1.8.7-p174 > nilruby-1.8.7-p174 > Time.zone = 'Pacific Time (US & Canada)'ruby-1.8.7-p174 > Time.zone=> #<ActiveSupport::TimeZone:0x1215a10 @utc_offset=-28800, @current_period=nil, @name="Pacific Time (US & Canada)", @tzinfo=#<TZInfo::DataTimezone: America/Los_Angeles>>

Note: above code is using rails 2.2.2 things maybe be different with newer versions?

editors note: In rails >= 3.0 all monkey patches have been moved to the core_ext namespace, so the above require does not extend Time. For later ActiveSupport versions use the following:

require 'active_support/core_ext/time/zones'


You can set the timezone with values from 2 sources, its own ActiveSupport short list (~137 values, see ActiveSupport::TimeZone.all to fetch them) or from the IANA names (~ 590 values). In this last case you can use the tzinfo gem (a dependency of ActiveSupport) to get the list or to instance a TZInfo::TimezoneProxy :

e.g.

ActiveSupport::TimeZone.all.map &:nameTime.zone = ActiveSupport::TimeZone.all.firstTime.zone = ActiveSupport::TimeZone.all.first.nameTime.zone = ActiveSupport::TimeZone.new "Pacific Time (US & Canada)"Time.zone = ActiveSupport::TimeZone.find_tzinfo "Asia/Tokyo"

List all countries, all timezones:

TZInfo::Country.all.sort_by { |c| c.name }.each do |c|  puts c.name # E.g. Norway  c.zones.each do |z|    puts "\t#{z.friendly_identifier(true)} (#{z.identifier})" # E.g. Oslo (Europe/Oslo)  endend