Ruby-on-rails 如何在 Rails 中获得 UTC 偏移量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5487876/
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
How can I get the utc offset in Rails?
提问by Lucas Renan
I need the utc offset from the timezone specified.
我需要指定时区的 utc 偏移量。
回答by lee
If you need to take daylight savings time into account, you can use something like this:
如果您需要考虑夏令时,您可以使用以下方法:
Time.now.in_time_zone('America/New_York').utc_offset
回答by steenslag
require 'time'
p Time.zone_offset('EST') #=> -18000 #(-5*60*60)
回答by fl00r
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
回答by William
If you have a ActiveSupport::TimeWithZoneobject, you can call time_zone.utc_offseton it. So, for example, Time.zone.now.time_zone.utc_offset.
如果你有一个ActiveSupport::TimeWithZone对象,你可以调用time_zone.utc_offset它。因此,例如,Time.zone.now.time_zone.utc_offset。
EDIT: You can also use the gmt_offsetinstance method on normal Timeobjects.
编辑:您也可以gmt_offset在普通Time对象上使用实例方法。
回答by timmcliu
If you are storing a user's timezone as a Time.zone.namestring such as 'Eastern Time (US & Canada)'as outlined in http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.htmland want to get the timezone offset you can do this:
如果您将用户的时区存储为Time.zone.name字符串,如http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html 中'Eastern Time (US & Canada)'所述,并且想要获取时区偏移量,您可以执行以下操作:
ActiveSupport::TimeZone.new(user.time_zone).utc_offset / 3600
# => -5
回答by Dorian
I use Time.zone.utc_offset / 1.hourto get the offset in hours (e.g.: -8for San Francisco)
我用来Time.zone.utc_offset / 1.hour以小时为单位获得偏移量(例如:-8对于旧金山)
回答by colemerrick
Time.now.in_time_zone('Europe/London').formatted_offset
# => "+01:00"
For a string arguably more usable...
对于一个可以说更有用的字符串......
回答by pjammer
Just to complete the loop here, right now I use:
只是为了完成这里的循环,现在我使用:
@course.start.utc_offset/60/60in order to get the # of hours needed. Jquery countdown needs just -5 or +3 in their timezoneargument.
@course.start.utc_offset/60/60为了获得所需的小时数。Jquery 倒计时在他们的timezone参数中只需要 -5 或 +3 。
Your welcome google.
你的欢迎谷歌。

