使用ActiveSupport的默认TimeZone(不带Rails)

Lan*_*ard 9 ruby timezone activesupport

如何在ActiveSupport中设置默认TimeZone?

这是发生了什么:

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
Run Code Online (Sandbox Code Playgroud)

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

hou*_*se9 7

在rails中,它通过rails初始化程序在environment.rb中设置

Rails::Initializer.run do |config|
    config.time_zone = 'Pacific Time (US & Canada)'
    # ...
Run Code Online (Sandbox Code Playgroud)

我刚做了一个测试,当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>>
Run Code Online (Sandbox Code Playgroud)

注意:上面的代码使用的是rails 2.2.2.新版本的内容可能有所不同?

编者注:在rails> = 3.0中,所有的猴子补丁都已移动到core_ext命名空间,因此上述要求不会扩展Time.对于更高ActiveSupport版本,请使用以下

require 'active_support/core_ext/time/zones'
Run Code Online (Sandbox Code Playgroud)


Meg*_*Tux 6

您可以使用来自 2 个来源的值设置时区,其自己的 ActiveSupport 简短列表(约 137 个值,请参阅ActiveSupport::TimeZone.all以获取它们)或来自IANA 名称(约 590 个值)。在最后一种情况下,您可以使用tzinfo gem(ActiveSupport 的依赖项)来获取列表或实例化TZInfo::TimezoneProxy

例如

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"
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)