如何让 Rails 将时间解释为处于特定时区? [英] How to get Rails to interpret a time as being in a specific time zone?

查看:42
本文介绍了如何让 Rails 将时间解释为处于特定时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Ruby 1.8.7, how to set the time zone of a time?

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

In the following examples, my system time zone is PST (-8:00 hours from UTC)

给定时间(2011 年 2 月 21 日,20:45),假设时间在美国东部时间:

Given a time (21 Feb 2011, 20:45), presume that the time is in 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)

But, the output I want is: Mon Feb 21 20:45:00 -0500 2011 (Note the -0500 (EST) as opposed to -0800 (PST) and the hour is same, i.e. 20, not 23)

我设法让它起作用,但我不喜欢它:

I managed to get this to work, but I don't like it:

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 以便我可以将其传递给 change 方法?

Question: Now, is there a way to determine the accurate(i.e. catering for daylight saving time etc) UTC offset from Time.zone so that I can pass it to the change method?

参考:DateTime::change方法

感谢@ctcherry 的帮助!

Thanks to @ctcherry for all the help!

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

Determine the accurate time zone info from Time.zone:

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

推荐答案

在 ruby​​ 1.8.7 中,根据文档的要求似乎不是很容易:

In ruby 1.8.7 it doesn't appear to be very easy to do what are asking for according to the documentation:

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

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

However in 1.9 it looks a lot easier by passing the timezone offset to the localtime() method on a Time object:

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

更新

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

The offset for Time.zone is easy since its an object on its own: (This is in a Rails console)

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" 

这篇关于如何让 Rails 将时间解释为处于特定时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆