Rails 5 introduces country_zones helper method

Mohit Natoo

Mohit Natoo

June 1, 2016

This blog is part of our  Rails 5 series.

Before Rails 5, we could fetch all time zones for US by using us_zones method as follows.

1
2> puts ActiveSupport::TimeZone.us_zones.map(&:to_s)
3(GMT-10:00) Hawaii
4(GMT-09:00) Alaska
5(GMT-08:00) Pacific Time (US & Canada)
6(GMT-07:00) Arizona
7(GMT-07:00) Mountain Time (US & Canada)
8(GMT-06:00) Central Time (US & Canada)
9(GMT-05:00) Eastern Time (US & Canada)
10(GMT-05:00) Indiana (East)
11

Such functionality of getting all the TimeZone objects for a country was implemented only for one country, US.

The TimeZone class internally uses the TzInfo gem which does have an api for providing timezones for all the countries.

Realizing this, the Rails community decided to introduce a helper method country_zones to ActiveSupport::TimeZone class that is able to fetch a collection of TimeZone objects belonging to a country specified by its ISO 3166-1 Alpha2 code.

1
2> puts ActiveSupport::TimeZone.country_zones('us').map(&:to_s)
3(GMT-10:00) Hawaii
4(GMT-09:00) Alaska
5(GMT-08:00) Pacific Time (US & Canada)
6(GMT-07:00) Arizona
7(GMT-07:00) Mountain Time (US & Canada)
8(GMT-06:00) Central Time (US & Canada)
9(GMT-05:00) Eastern Time (US & Canada)
10(GMT-05:00) Indiana (East)
11
12>puts ActiveSupport::TimeZone.country_zones('fr').map(&:to_s)
13 (GMT+01:00) Paris
14

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.