Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Rails TimeZone names from obsolete TZInfo identifiers?

There is already a question which answers how to convert "America/Los_Angeles" to "Pacific Time (US & Canada)". However I want to convert "US/Pacific" and other obsolete time zones to Rails TimeZone. I am unable to find anything in the library which helps me accomplish this.

like image 885
user842563 Avatar asked Oct 16 '13 07:10

user842563


3 Answers

From the Rails ActiveSupport::TimeZone docs:

The version of TZInfo bundled with Active Support only includes the definitions necessary to support the zones defined by the TimeZone class. If you need to use zones that aren’t defined by TimeZone, you’ll need to install the TZInfo gem (if a recent version of the gem is installed locally, this will be used instead of the bundled version.)

Personally, I think Rails time zones are silly. They are arbitrarily limited to what Rails describes as "a meaningful subset of 146 zones". But they do nothing to explain how they determine which zones are "meaningful" and which are discarded.

Identifiers such as "US/Pacific" are known as "links" or "aliases" in the TZDB data. I could see that perhaps they might be omitted from Rails, but there are many other real-world time zones that are missing entirely.

The only place I've every seen Rails time zones identifiers in the real world is in the Twitter API. On the other hand, IANA/TZDB identifiers are ubiquitous.

The best advice I can offer is to forget about Rails time zones, and just use the Ruby TZInfo Gem directly. It has the full TZDB implementation with all zones, including aliases.

If you really must continue to use Rails zones, you could first use TZInfo to resolve the alias to the actual zone, and then see if that that zone is in the Rails MAPPING dictionary. For example:

"US/Pacific" => "America/Los_Angeles"                    (via TZInfo)

"America/Los_Angeles" => "Pacific Time (US & Canada)"    (via Rails MAPPING)

I believe when you load "US/Pacific" via TZInfo, it will be subclassed as a LinkedTimezoneInfo object, so you could use the link_to_identifier attribute from there.

like image 197
Matt Johnson-Pint Avatar answered Oct 19 '22 21:10

Matt Johnson-Pint


You can do it by this:

arr = TZInfo::Timezone.all_country_zone_identifiers.collect { |x| x + " " + ActiveSupport::TimeZone[x].formatted_offset }
arr.sort
like image 3
Harshit Agarwal Avatar answered Oct 19 '22 21:10

Harshit Agarwal


In this command will display the 144 timezone names.

ActiveSupport::TimeZone.zones_map

like image 1
thiyaram Avatar answered Oct 19 '22 22:10

thiyaram