Varinder Singh
Varinder Singh

Reputation: 1590

How to get tz identifier string from utc offset

How do I get timezone in tzinfo format i.e America/Toronto from utc offset in seconds while taking into consideration the DST changes.

For example DST settings last changed at 2:00 AM , March 9,2014. See offset difference

Varinder $ irb

2.1.0 :001 > Time.local(2014,03,9,1,59) 
 => 2014-03-09 01:59:00 -0500 

2.1.0 :002 > Time.local(2014,03,9,2,00) 
 => 2014-03-09 03:00:00 -0400 
2.1.0 :003 >

2.1.0 :006 > Time.local(2014,03,9,2,00).zone
 => "EDT"  # I need America/Toronto format

For both these time examples calculated tzinfo string should be same because only difference in offset is due to DST.

Upvotes: 2

Views: 1082

Answers (2)

Dmitry Lihachev
Dmitry Lihachev

Reputation: 504

Try this

zone_abbr = Time.local(2014,03,9,2,00).zone
ActiveSupport::TimeZone.
  all.
  select{|tz| tz.tzinfo.current_period.abbreviation.to_s == zone_abbr}.
  map(&:tzinfo).
  map(&:name)

For "EDT" this code returns ["America/New_York", "America/Indiana/Indianapolis"]

Upvotes: 1

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

You'll have to figure out the DST issues, but this might get you there (I'm in PST...)

> offset = Time.local(2014,03,9,1,59).utc_offset
=> -28800
> ActiveSupport::TimeZone.all.select{|tz| tz.utc_offset == offset}
=> [#<ActiveSupport::TimeZone:0x007fbcacd075a8 @name="Pacific Time (US & Canada)", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: America/Los_Angeles>, @current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1394359200>,#<TZInfo::TimezoneOffsetInfo: -28800,3600,PDT>>,#<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1414918800>,#<TZInfo::TimezoneOffsetInfo: -28800,0,PST>>>>, #<ActiveSupport::TimeZone:0x007fbcacd07530 @name="Tijuana", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: America/Tijuana>, @current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1394359200>,#<TZInfo::TimezoneOffsetInfo: -28800,3600,PDT>>,#<TZInfo::TimezoneTransitionInfo: #<TZInfo::TimeOrDateTime: 1414918800>,#<TZInfo::TimezoneOffsetInfo: -28800,0,PST>>>>]

Upvotes: 1

Related Questions