Ruby / Rails - 更改时间的时区,而不更改该值 [英] Ruby / Rails - Change the timezone of a Time, without changing the value
问题描述
我有一个记录 foo
在数据库中有:start_time
和:timezone
属性
I have a record foo
in the database which has :start_time
and :timezone
attributes.
:start_time
是UTC的时间 - 2001-01-01 14:20:00
。
例如:timezone
是一个字符串 - America / New_York
。
The :start_time
is a Time in UTC - 2001-01-01 14:20:00
, for example.
The :timezone
is a string - America/New_York
, for example.
我想创建一个新的Time对象,其值为:start_time
,但其时区由指定:timezone
。我不想加载:start_time
然后转换为:timezone
,因为Rails将会很聪明并且更新来自UTC的时间与该时区一致。
I want to create a new Time object with the value of :start_time
but whose timezone is specified by :timezone
. I do not want to load the :start_time
and then convert to :timezone
, because Rails will be clever and update the time from UTC to be consistent with that timezone.
目前,
t = foo.start_time
=> 2000-01-01 14:20:00 UTC
t.zone
=> "UTC"
t.in_time_zone("America/New_York")
=> Sat, 01 Jan 2000 09:20:00 EST -05:00
相反,我想看看
=> Sat, 01 Jan 2000 14:20:00 EST -05:00
ie。我想做:
t
=> 2000-01-01 14:20:00 UTC
t.zone = "America/New_York"
=> "America/New_York"
t
=> 2000-01-01 14:20:00 EST
推荐答案
听起来像你想要的东西沿着
Sounds like you want something along the lines of
ActiveSupport::TimeZone.new('America/New_York').local_to_utc(t)
这表示将本地时间(使用区域)转换为utc。如果你有 Time.zone
,那么你当然可以
This says convert this local time (using the zone) to utc. If you have Time.zone
set then you can of course to
Time.zone.local_to_utc(t)
这不会使用附加到t的时区 - 它假设这是您正在转换的时区的本地。
This won't use the timezone attached to t - it assumes that it's local to the time zone you are converting from.
在这里保护的一个边缘案例是DST转换:您指定的本地时间可能不存在或可能不明确。
One edge case to guard against here is DST transitions: the local time you specify may not exist or may be ambiguous.
这篇关于Ruby / Rails - 更改时间的时区,而不更改该值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!