>> DateTime.now.in_time_zone.class
=> ActiveSupport::TimeWithZone
>> Time.zone.now.class
=> ActiveSupport::TimeWithZone
>> DateTime.now.in_time_zone.offset
=> (0/1)
>> Time.zone.now.offset
NoMethodError: undefined method `offset' for Mon, 28 Aug 2017 17:34:46 CEST +02:00:Time
from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/activesupport-4.1.16/lib/active_support/time_with_zone.rb:364:in `method_missing'
from (irb):287
from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands/console.rb:90:in `start'
from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands/console.rb:9:in `start'
from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands/commands_tasks.rb:69:in `console'
from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /Users/Magne/.rvm/gems/ruby-2.3.1/gems/railties-4.1.16/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
答案 0 :(得分:2)
ActiveSupport::TimeWithZone
没有offset
方法。相反,该呼叫由method_missing
处理:
将缺少的方法发送到
time
实例,并将结果包装到具有现有time_zone
的新TimeWithZone中。
适用于DateTime
,因为它会响应offset
:
DateTime.instance_methods.include? :offset
#=> true
Time
失败,因为它没有:
Time.instance_methods.include? :offset
#=> false