Rails DateTime object isn't what I expect
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开发者_Go百科 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.
DateTime
is a core class, and part of Date
. It is available if you require 'date'
in your code; You don't have to use Rails to access it.
require 'date'
asdf = DateTime.parse(`date`)
asdf # => #<DateTime: 2010-12-10T21:41:59-07:00 (212158802519/86400,-7/24,2299161)>
asdf.class # => DateTime
asdf.to_s # => "2010-12-10T21:41:59-07:00"
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:
require 'active_support/all'
asdf.in_time_zone # => Fri, 10 Dec 2010 21:43:42 -0700
or
require 'active_support/core_ext'
asdf.in_time_zone # => Fri, 10 Dec 2010 21:59:48 -0700
Ruby's Time class has good support for timezones also, so you might want to get familiar with it too.
You don't need whole Rails stack for timezone support. You can install and use just active_support. But you can as well check out tzinfo
gem.
精彩评论