【发布时间】:2011-07-26 03:56:15
【问题描述】:
我需要指定时区的 UTC 偏移量。
【问题讨论】:
标签: ruby-on-rails ruby datetime timezone
我需要指定时区的 UTC 偏移量。
【问题讨论】:
标签: ruby-on-rails ruby datetime timezone
如果您需要考虑夏令时,您可以使用以下方法:
Time.now.in_time_zone('America/New_York').utc_offset
【讨论】:
Time.zone.utc_offset 没有的正确偏移量。
ActiveSupport::TimeWithZone
Time.zone.utc_offset 效果更好,它莫名其妙地不考虑夏令时。
require 'time'
p Time.zone_offset('EST') #=> -18000 #(-5*60*60)
【讨论】:
config.time_zone = 'Berlin' 和 config.active_record.default_timezone = 'Berlin' (在我的情况下,没有它不会反映夏令时正确调整)
config.active_record.default_timezone 更改为 :local 而不是 'Santiago',否则每个 DateTime 字段都会更改为 nil。 Time.zone_offset 会正确处理夏令时吗?
Time.now.utc_offset 也适用于 DST,而 Time.zone.utc_offset 则不适用。
Time.now.in_time_zone('Europe/London').formatted_offset
# => "+01:00"
对于一个可以说更有用的字符串...
【讨论】:
my_date_time = DateTime.new(2011, 3, 29, 20)
#=> Tue, 29 Mar 2011 20:00:00 +0000
#will return the same time but with another offset
my_date_time.change(:offset => "+0100")
#=> Tue, 29 Mar 2011 20:00:00 +0100
#will return time for other offset
my_date_time.in_time_zone(-1)
#=> Tue, 29 Mar 2011 19:00:00 -0100
【讨论】:
如果你有一个ActiveSupport::TimeWithZone 对象,你可以在它上面调用time_zone.utc_offset。所以,例如,Time.zone.now.time_zone.utc_offset。
编辑:您还可以对普通的 Time 对象使用 gmt_offset 实例方法。
【讨论】:
如果您将用户的时区存储为Time.zone.name 字符串,例如'Eastern Time (US & Canada)',如http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html 中所述,并且想要获取时区偏移量,您可以这样做:
ActiveSupport::TimeZone.new(user.time_zone).utc_offset / 3600
# => -5
【讨论】:
Time.now.in_time_zone(user.time_zone).utc_offset / 3600
我使用Time.zone.utc_offset / 1.hour 以小时为单位获取偏移量(例如:-8 表示旧金山)
【讨论】:
只是为了完成这里的循环,我现在使用:
@course.start.utc_offset/60/60 以获得所需的小时数。 Jquery 倒计时在其timezone 参数中只需要-5 或+3。
欢迎您的谷歌。
【讨论】: