Ruby 带ActiveSupport的默认时区(不带Rails)

Ruby 带ActiveSupport的默认时区(不带Rails),ruby,timezone,activesupport,Ruby,Timezone,Activesupport,如何在ActiveSupport中设置默认时区 下面是正在发生的事情: 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 默认情况下,如何将其设置为当前位置?在rails中,它通过ra

如何在ActiveSupport中设置默认时区

下面是正在发生的事情:

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

默认情况下,如何将其设置为当前位置?

在rails中,它通过rails初始值设定项在environment.rb中设置

Rails::Initializer.run do |config|
    config.time_zone = 'Pacific Time (US & Canada)'
    # ...
我刚刚做了一个测试,当config.time_zone被注释掉时,time.zone在rails项目中也将返回nil;因此,我猜没有“默认值”,它只是在初始值设定项中设置的

我猜你已经知道这会“起作用”了

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>>

您可以使用来自2个源、其自己的ActiveSupport短列表(~137个值,请参阅获取它们)或(~590个值)的值设置时区。在最后一种情况下,您可以使用(ActiveSupport的依赖项)获取列表或实例:

e、 g

列出所有国家、所有时区:

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

我试图在rails之外使用它:)我知道;我想说的是,即使在rails中,它似乎也没有使用默认值,似乎您需要自己在irb中设置Time.zone?但也许我错了?
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"
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