I’m a Java developer who is very new to Ruby so if this question is a little too basic, please go easy on me. 🙂 I’m here to learn if someone can point me in the right direction.
I’m writing an application that deals with times and will need to take time zones into account. I was curious what Ruby offers for dealing with timezones and I found that Rails provides a DateTime class that should do what I need. http://api.rubyonrails.org/classes/DateTime.html#method-i-in_time_zone
However, when I create a DateTime, it doesn’t seem to have the methods I expect. Can someone explain what is going on here? Here is what I’m seeing in irb:
>> dt = DateTime.now
NameError: uninitialized constant DateTime
from (irb):1
>> require 'rails'
=> true
>> dt = DateTime.now
=> #<DateTime: 212158799144191849/86400000000,-1/4,2299161>
>> dt.respond_to? "in_time_zone"
=> false
Since DateTime isn’t defined until I require rails, I assumed I was using the Rails DateTime but it doesn’t seem to have the methods I’m expecting based on the documentation.
DateTimeis a core class, and part ofDate. It is available if yourequire 'date'in your code; You don’t have to use Rails to access it.The class you’re after is part of ActiveSupport, which is part of Rails, but you don’t have to load Rails to access it:
or
Ruby’s Time class has good support for timezones also, so you might want to get familiar with it too.