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.
> puts ActiveSupport::TimeZone.us_zones.map(&:to_s)
(GMT-10:00) Hawaii
(GMT-09:00) Alaska
(GMT-08:00) Pacific Time (US & Canada)
(GMT-07:00) Arizona
(GMT-07:00) Mountain Time (US & Canada)
(GMT-06:00) Central Time (US & Canada)
(GMT-05:00) Eastern Time (US & Canada)
(GMT-05:00) Indiana (East)
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.
> puts ActiveSupport::TimeZone.country_zones('us').map(&:to_s)
(GMT-10:00) Hawaii
(GMT-09:00) Alaska
(GMT-08:00) Pacific Time (US & Canada)
(GMT-07:00) Arizona
(GMT-07:00) Mountain Time (US & Canada)
(GMT-06:00) Central Time (US & Canada)
(GMT-05:00) Eastern Time (US & Canada)
(GMT-05:00) Indiana (East)
>puts ActiveSupport::TimeZone.country_zones('fr').map(&:to_s)
(GMT+01:00) Paris
If this blog was helpful, check out our full blog archive.