Is there a way to get a TZInfo style string for the local timezone?

990 views Asked by At

I need to try to get a TZInfo style string a-la 'America/New_York' representing the local timezone of the system I'm on. I can't figure out how to do it.

Time.zone

#<ActiveSupport::TimeZone:0x007ff2e4f89240 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffsetInfo: 0,0,UTC>>>>

Here the TimezoneProxy#Etc/UTC field is the style I want but is UTC not local time.

Time.now.zone

"EST"

Here the "EST" is not what I want and I don't see a way to pass Time.now or EST to TZInfo to get what I want?

Is there a way to get "America/New_York" or even a list of all equivalent timezone strings based on my current timezone?

1

There are 1 answers

1
Dmitry Lihachev On

You can try to find all EST aliases with:

current_tz = ActiveSupport::TimeZone['EST']
ActiveSupport::TimeZone.
  all.
  select{|tz| tz.utc_offset == current_tz.utc_offset }.
  map(&:tzinfo).
  map(&:name).
  uniq

will produce

["America/Bogota", "EST", "America/New_York", "America/Indiana/Indianapolis", "America/Lima"]

But I think this is incorrect, because of daylight saving issues. More correct code:

current_tz = ActiveSupport::TimeZone['EST']
ActiveSupport::TimeZone.
  all.
  select{|tz| 
    tz.utc_offset == current_tz.utc_offset && 
      tz.tzinfo.current_period.dst? == current_tz.tzinfo.current_period.dst? 
  }.
  map(&:tzinfo).
  map(&:name).
  uniq

will produce

["America/Bogota", "EST", "America/Lima"]