Search code examples
rubydatetimetimezonezone

NoMethodError: undefined method `zone' for Time:Class


How do i use Time.zone in ruby if I am not using rails I want to do Time.now but that's available in rails but not ruby

I thought that

require 'time'

would fix this and make it available in ruby but it didn't and I get

NoMethodError: undefined method `zone' for Time:Class

Solution

  • You've tried to use zone as if it were a class method (Time.zone) [1]. If you want to use a class method:

    1.9.3-p448 :007 > Time.now.zone
    => "EDT" 
    

    But Time.now is just a nice way of instantiating your own instance of Time[2]. So you're really just doing this (calling an instance method):

    1.9.3-p448 :009 > time = Time.new
    => 2014-04-09 15:14:01 -0400 
    1.9.3-p448 :010 > time.zone
    => "EDT" 
    

    [1] http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

    [2] http://ruby-doc.org/core-1.9.3/Time.html#method-c-now