【发布时间】:2011-07-01 17:57:02
【问题描述】:
在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))
问题:现在,有没有办法从Time.zone 确定 准确(即适应夏令时等)UTC 偏移量,以便我可以通过它换方法?
更新(更好的版本)
感谢@ctcherry 提供的所有帮助!
从Time.zone确定准确的时区信息:
DateTime.civil(2011,02,21,20,45,0,Rational((Time.zone.tzinfo.current_period.utc_offset / 3600), 24))
【问题讨论】:
-
此解决方案可能对您有所帮助stackoverflow.com/questions/4262550/…
标签: ruby ruby-on-rails-3