我使用的是 Ruby 2.2.1 并安装了 active_support 4.2,所以我想使用
Time.zone.parse('2007-02-10 15:30:45')
如此处所述:http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html
但即使在要求
active_support
和 active_support/time_with_zone
之后,我似乎 Time.zone
仍然不起作用。观察:
2.2.1 :002 > require "active_support"
=> true
2.2.1 :003 > Time.zone
NoMethodError: undefined method `zone' for Time:Class
2.2.1 :004 > require "active_support/time_with_zone"
=> true
2.2.1 :005 > Time.zone
NoMethodError: undefined method `zone' for Time:Class
发生什么事了?
zone
类的Time
类方法实际上在active_support/core_ext/time/zones
中。如果您确实想使用 Time.zone
,则可以要求该课程,但更好的方法可能需要 active_support/all
建议的解决方案
require "active_support/all"
如果您想查看 active_support 的源代码,请查看 github repo
active_support/time_with_zone
提供了ActiveSupport::TimeWithZone
类,但它没有扩展核心Time
类。
active_support/time
来代替:
require 'active_support'
require 'active_support/time'
Time.zone = 'Eastern Time (US & Canada)' #=> "Eastern Time (US & Canada)"
Time.zone.parse('2007-02-10 15:30:45') #=> Sat, 10 Feb 2007 15:30:45 EST -05:00
尝试
require 'active_support/all'
而不是
require "active_support"
如果您不想加载所有主动支持:
require "active_support"
require "active_support/core_ext/numeric/time"