开发者

Making sense of Rails TimeZone

Consider this gist: https://gist.github.com/752934

When converting from String to Time everything goes well. It returns as UTC. H开发者_StackOverflow社区owever, when you convert from time to time it returns as WEST instead of UTC (or returning self: http://api.rubyonrails.org/classes/Time.html#method-i-to_time)

Any idea on why is the time zone being changed from UTC to WEST?

Thanks in advance, DBA


I am guessing it suffers from the same problem as DateTime.to_time. This was submitted as a bug in Ruby, but rejected. More info here:

http://redmine.ruby-lang.org/issues/show/3737

UPDATE: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/time/conversions.rb

Looks like API doc is out of date. There is a condition on the method to check if to_time is already defined. So looks like its not even hitting this ext method:

  # A method to keep Time, Date and DateTime instances interchangeable on conversions.
  # In this case, it simply returns +self+.
  def to_time
    self
  end unless method_defined?(:to_time)

Here is the commit: https://github.com/rails/rails/blob/4817bf94d135c44ddfae1a30acb15de989e3c86c/activesupport/lib/active_support/core_ext/time/conversions.rb

I tested out monkey patching and it works like you would expect:

ruby-1.9.2-p0 > class Time
ruby-1.9.2-p0 ?>  def to_time
ruby-1.9.2-p0 ?>    self
ruby-1.9.2-p0 ?>  end
ruby-1.9.2-p0 ?>end
 => nil 
ruby-1.9.2-p0 > Time.zone = Time.zone_default = "UTC"
 => "UTC" 
ruby-1.9.2-p0 > t = "2008-04-01".to_time
 => 2008-04-01 00:00:00 UTC 
ruby-1.9.2-p0 >  p t.zone, t.to_time.zone
"UTC"
"UTC"
 => ["UTC", "UTC"] 

I would consider this a bug

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜