Rails:将UTC日期时间转换为另一个时区

125
在Ruby/Rails中,如何将UTC日期时间转换为另一个时区?
6个回答

230
time.in_time_zone(time_zone)

示例:

zone = ActiveSupport::TimeZone.new("Central Time (US & Canada)")
Time.now.in_time_zone(zone)
或者只是
Time.now.in_time_zone("Central Time (US & Canada)")

您可以通过以下方式找到ActiveSupport时区名称:

ActiveSupport::TimeZone.all.map(&:name)
# or for just US
ActiveSupport::TimeZone.us_zones.map(&:name)

17
如果要在Rails之外使用,请先运行require 'active_support/time' - sunaku
3
您可以通过运行 rake time:zones:all 列出所有的时区。另外请参考 rake -D time。在 config/application.rb 中设置默认的时区。 - user664833
1
在Rails中,通常使用ActiveSupport :: TimeWithZone而不是DateTime。所有这些代码都适用于ruby DateTime对象和Time对象。 - mckeed
1
你也可以从ActiveSupport::TimeZone documentation页面获取所有时区的列表。 - sameers
使用 in_time_zone('GMT') 进行 GMT 时间转换。很简单! - Dennis Hackethal
显示剩余3条评论

10
如果Time.zone是您所需的时区,那么您可以使用@date.to_time.to_datetime
> @date
=> Tue, 02 Sep 2014 23:59:59 +0000
> @date.class
=> DateTime
> @date.to_time
=> 2014-09-02 12:59:59 -1100
> @date.to_time.to_datetime
=> Tue, 02 Sep 2014 12:59:59 -1100 

2
无法在Rails 5上运行 Time.zone # => Europe/Paris my_date # => Wed, 29 Mar 2017 19:00:20 +0200 my_date.to_time # => "2017-03-29T17:00:20.000+00:00" my_date.to_time.to_datetime # => Wed, 29 Mar 2017 17:00:20 +0000 - Cyril Duchon-Doris

5

在纯 Ruby 中,只需使用require 'date',即可使用new_offset方法:

require 'date'

d=DateTime.parse('2000-01-01 12:00 +0200')
l=d.new_offset('-0700')
u=l.new_offset('UTC')
puts "#{u.strftime('%a %F %T %Z')}#{l.strftime('%a %F %T %Z')}"

经过测试,可以在Mac OS X 10.13上使用自带的Ruby 2.3.7。


3

试用ActiveSupport的TimeWithZone对象,并使用TimeZone进行操作。同时,ActiveSupport还提供了in_time_zone方法,可以将UTC时间转换为指定的TimeZone时区时间。mckeed的回答展示了代码。


我的类如何导入TimeWithZone的语法?或者说在Rails中我可以默认获取它吗? - Drew Johnson
1
我相信你默认就已经明白了。mckeed有你需要的代码,但你在irb中看不到它。你需要在Rails中运行它。 - Fred
你说得对 - 谢谢,弗雷德 - 它默认情况下是与Rails一起提供的。我曾经试图在irb中让它工作,但却是徒劳无功。 - Drew Johnson

3

如果你在Rails中处理ActiveRecord对象,使用Time.use_zone来设置每个请求的时区可能是一个好主意,这将覆盖config.time_zone中设置的默认时区。

更多细节可以参考https://stackoverflow.com/a/25055692/542995


0

我正在使用Rails 4中的simple_form,我刚刚添加了输入字段:

<%= f.input :time_zone, :as => :time_zone %>

随着迁移

class AddTimeZoneColumnToTextmessage < ActiveRecord::Migration
  def change
    add_column :textmessages, :time_zone, :string
  end
end

2
这并没有回答如何转换DateTime对象的问题。 - zykadelic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接