【问题标题】:Default TimeZone with ActiveSupport (without Rails)带 ActiveSupport 的默认时区(不带 Rails)
【发布时间】:2011-03-05 21:43:53
【问题描述】:

如何在 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

如何默认设置为当前位置?

【问题讨论】:

    标签: ruby timezone activesupport


    【解决方案1】:

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

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

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

    require 'active_support/core_ext/time/zones'
    

    【讨论】:

    • 我正在尝试在 Rails 之外使用它:)
    • 我知道;我要说的是,即使在rails中它似乎也没有使用默认值,看来您需要在irb中自己设置Time.zone?但话说回来,也许我错了?
    【解决方案2】:

    您可以使用来自 2 个来源、其自己的 ActiveSupport 短列表(约 137 个值,请参阅ActiveSupport::TimeZone.all 获取它们)或来自IANA names(约 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"
    

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 2012-11-25
      • 2011-05-20
      • 2014-08-17
      相关资源
      最近更新 更多