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

时间:2011-02-22 05:06:17

标签: ruby ruby-on-rails-3

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

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

给定时间(21 Feb 2011, 20:45),假定时间是在EST:

#this interprets the time as system time zone, i.e. 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))

问题:现在,有没有办法确定准确(即迎合夏令时等)UTC偏离Time.zone以便我可以把它传递给改变方法?

参考:DateTime::change method

更新(更好的版本)

感谢@ctcherry的所有帮助!

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

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

2 个答案:

答案 0 :(得分:1)

在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

<强>更新

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

ruby-1.8.7-p248 :001 > Time.zone
 => #<ActiveSupport::TimeZone:0x103150190 @current_period=nil, @name="Central Time (US & Canada)", @tzinfo=#<TZInfo::TimezoneProxy: America/Chicago>, @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" 

答案 1 :(得分:0)

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

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上测试的。