Ruby-on-rails Rails:将 UTC DateTime 转换为另一个时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2695837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:35:22  来源:igfitidea点击:

Rails: convert UTC DateTime to another time zone

ruby-on-railsrubydatetimeruntime

提问by Drew Johnson

In Ruby/Rails, how do I convert a UTC DateTime to another time zone?

在 Ruby/Rails 中,如何将 UTC DateTime 转换为另一个时区?

回答by mckeed

time.in_time_zone(time_zone)

Example:

例子:

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

or just

要不就

Time.now.in_time_zone("Central Time (US & Canada)")

You can find the names of the ActiveSupport time zones by doing:

您可以通过执行以下操作找到 ActiveSupport 时区的名称:

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

回答by vladCovaliov

if Time.zoneit's your desired time zone then you can use @date.to_time.to_datetime

如果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 

回答by jbyler

In plain ruby, with only require 'date', use the new_offsetmethod:

在普通的 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')}"

Tested with ruby 2.3.7 that came standard on Mac OS X 10.13.

使用在 Mac OS X 10.13 上标配的 ruby​​ 2.3.7 进行测试。

回答by zdk

Just in case, if you are dealing with ActiveRecord object in Rails.

以防万一,如果您在 Rails 中处理 ActiveRecord 对象。

It might be a good idea to use Time.use_zonefor a per request basis timezone that overrides the default timezone set in config.time_zone

Time.use_zone对于每个请求基础时区使用它可能是一个好主意,它会覆盖在config.time_zone

More details I explain at https://stackoverflow.com/a/25055692/542995

我在https://stackoverflow.com/a/25055692/542995解释了更多细节

回答by Fred

Try ActiveSupport's TimeWithZoneobjects manipulated with TimeZone. ActiveSupport also provides the in_time_zone method for converting a UTC time to a specified TimeZone time zone. mckeed's answer shows the code.

尝试使用 TimeZone 操作的ActiveSupport 的TimeWithZone对象。ActiveSupport 还提供了 in_time_zone 方法,用于将 UTC 时间转换为指定的 TimeZone 时区。mckeed 的回答显示了代码。

回答by maudulus

I'm using simple_form in Rails 4 and I just added the input field as

我在 Rails 4 中使用 simple_form,我刚刚将输入字段添加为

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

with the migration

随着迁移

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