Ruby/Rails - 更改时间的时区,而不更改值 [英] Ruby / Rails - Change the timezone of a Time, without changing the value

查看:23
本文介绍了Ruby/Rails - 更改时间的时区,而不更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有一个记录 foo,它有 :start_time:timezone 属性.

:start_time 是 UTC 时间 - 2001-01-01 14:20:00 例如.:timezone 是一个字符串 - 例如 America/New_York.

我想用 :start_time 的值创建一个新的 Time 对象,但它的时区由 :timezone 指定.我不想加载 :start_time 然后转换为 :timezone,因为 Rails 会很聪明并更新 UTC 时间以与该时区保持一致.>

目前,

t = foo.start_time=>2000-01-01 14:20:00 UTCt区=>世界标准时间"t.in_time_zone("美国/纽约")=>2000 年 1 月 1 日星期六 09:20:00 美国东部时间 -05:00

相反,我想看看

=>2000 年 1 月 1 日星期六 14:20:00 美国东部时间 -05:00

即.我想做:

t=>2000-01-01 14:20:00 UTCt.zone = "美国/纽约"=>美国/纽约"吨=>2000-01-01 14:20:00 美国东部时间

解决方案

听起来你想要一些类似

的东西

ActiveSupport::TimeZone.new('America/New_York').local_to_utc(t)

这表示将此本地时间(使用区域)转换为 UTC.如果你设置了 Time.zone 那么你当然可以

Time.zone.local_to_utc(t)

这不会使用附加到 t 的时区 - 它假定它是您正在转换的时区的本地时区.

这里要防范的一个边缘情况是 DST 转换:您指定的本地时间可能不存在或可能不明确.

I have a record foo in the database which has :start_time and :timezone attributes.

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.

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.

Currently,

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

Instead, I want to see

=> Sat, 01 Jan 2000 14:20:00 EST -05:00

ie. I want to do:

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)

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)

This won't use the timezone attached to t - it assumes that it's local to the time zone you are converting from.

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屋!

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