开发者

How can I get the utc offset in Rails?

I nee开发者_运维技巧d the utc offset from the timezone specified.


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


require 'time'

p Time.zone_offset('EST') #=> -18000  #(-5*60*60)


Time.now.in_time_zone('Europe/London').formatted_offset
# => "+01:00"

For a string arguably more usable...


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


If you are storing a user's timezone as a Time.zone.name string such as 'Eastern Time (US & Canada)' as outlined in http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html and want to get the timezone offset you can do this:

ActiveSupport::TimeZone.new(user.time_zone).utc_offset / 3600
# => -5


If you have a ActiveSupport::TimeWithZone object, you can call time_zone.utc_offset on it. So, for example, Time.zone.now.time_zone.utc_offset.

EDIT: You can also use the gmt_offset instance method on normal Time objects.


I use Time.zone.utc_offset / 1.hour to get the offset in hours (e.g.: -8 for San Francisco)


Just to complete the loop here, right now I use:

@course.start.utc_offset/60/60 in order to get the # of hours needed. Jquery countdown needs just -5 or +3 in their timezone argument.

Your welcome google.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜