Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default TimeZone with ActiveSupport (without Rails)

How does the default TimeZone get set in ActiveSupport?

Here's what's happening:

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.zone
ruby-1.8.7-p174 > nil

How do I set that to the current location by default?

like image 745
Lance Avatar asked Jun 20 '10 01:06

Lance


2 Answers

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.zone
ruby-1.8.7-p174 > nil
ruby-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'
like image 134
house9 Avatar answered Nov 04 '22 09:11

house9


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 &:name

Time.zone = ActiveSupport::TimeZone.all.first

Time.zone = ActiveSupport::TimeZone.all.first.name

Time.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)
  end
end
like image 30
MegaTux Avatar answered Nov 04 '22 08:11

MegaTux