如何让Rails将时间解释为在特定时区?

在Ruby 1.8.7中,如何设置时区的时区?

在以下示例中,我的系统时区是PST(距UTC的-8:00小时)

给定时间( 21 Feb 2011, 20:45 ),假定时间是在美国东部时间:

 #this interprets the time as system time zone, ie PST Time.local(2011,02,21,20,45) #=> Mon Feb 21 20:45:00 -0800 2011 #this **converts** the time into EST, which is wrong! Time.local(2011,02,21,20,45).in_time_zone "Eastern Time (US & Canada)" #=> Mon, 21 Feb 2011 23:45:00 EST -05:00 

但是,我想要的输出是: Mon Feb 21 20:45:00 -0500 2011 (注意-0500(EST)而不是-0800(PST),小时相同,即20 ,而不是23

更新(请参阅下面的更好版本)

我设法让这个工作,但我不喜欢它:

 DateTime.new(2011,02,21,20,45).change :offset => -(300.0 / 1440.0) # => Mon, 21 Feb 2011 20:45:00 +0500 Where 300 = 5 hrs x 60 minutes 1440 = number of minutes in a day or the "right" way: DateTime.civil(2011,02,21,20,45,0,Rational(-5, 24)) 

:现在,有没有办法确定Time.zone准确 (即迎合夏令时等)UTC偏移量,以便我可以将其传递给更改方法?

参考: DateTime::change方法

更新(更好的版本)

感谢@ctcherry提供的所有帮助!

Time.zone确定准确的时区信息:

 DateTime.civil(2011,02,21,20,45,0,Rational((Time.zone.tzinfo.current_period.utc_offset / 3600), 24)) 

在ruby 1.8.7中,根据文档执行所要求的内容似乎并不容易:

http://www.ruby-doc.org/core-1.8.7/classes/Time.html

但是在1.9中,通过将时区偏移量传递给Time对象上的localtime()方法看起来要容易得多:

http://www.ruby-doc.org/core/classes/Time.html#M000346

UPDATE

Time.zone的偏移很容易,因为它自己是一个对象:(这是在Rails控制台中)

 ruby-1.8.7-p248 :001 > Time.zone => #, @utc_offset=nil> ruby-1.8.7-p248 :002 > Time.zone.utc_offset => -21600 ruby-1.8.7-p248 :003 > Time.zone.formatted_offset => "-06:00" 

所以我认为这将(几乎)完成你想要的:

 require 'time' t = "21 Feb 2011, 20:45" Time.parse(t) # => Mon Feb 21 20:45:00 -0700 2011 t += " -05:00" # this is the trick Time.parse(t) # => Mon Feb 21 18:45:00 -0700 2011 

它仍然会根据您的系统时区返回时间,但实际时间是您正在寻找的正确时间。

顺便说一下,这是在1.8.7-p334上测试的。