TimeZone selection
Written by matt on December 21st, 2007
Supporting TimeZones is a serious pain in a developer's neck. Thankfully, Rails comes with a bunch of tools making our life easier. One of my Rails patch just got merged in Rails Edge (Future Rails 2.1) and I believe it will make my life just a tiny be more enjoyable.
Let's look at a simple scenario, your application has many users and each user has the option of setting his own TimeZone. Most of your users are in the US and actually on the West Coast. You probably don't want to list all the time zones on earth, and you don't really want to include a blank option. What we want is to have a list of top priority time zones (US zones) and to pre select the most comment zone. (L.A. / PST)
I won't go into TZ support in the back-end, check this post, this other one or yet that one for more information.
Let's look at our views, option one, you want to use the Rails built-in TimeZones:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<% form_for :user do |f| -%> <p> <label for="name">Name: <em>(full name)</em></label><br/> <%= f.text_field :name %> </p> <p> <label>Default timezone:</label><br/> <%= f.time_zone_select ('time_zone', TimeZone.us_zones, :default => "Pacific Time (US & Canada)") %> </p> <div class="actions"><%= submit_tag 'register' %></div> <% end -%> |

Option 2, we are using TZinfo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<% form_for :user do |f| -%> <p> <label for="name">Name: <em>(full name)</em></label><br/> <%= f.text_field :name %> </p> <p> <label>Default timezone:</label><br/> <%= f.time_zone_select('time_zone', TZInfo::Timezone.us_zones, :default => "America/Los_Angeles", :model => TZInfo::Timezone %> </p> <div class="actions"><%= submit_tag 'register' %></div> <% end -%> |

Obviously, the default timezone is used only if the user didn't set one already.
Pretty simple feature but hopefully quite helpful!
Comments
-
I'm mostly excited to find out that timezoneselect exists!
-
Very nice patch Matt :)
db:migrate:redo and db:migrate:reset was useful too - I was just using it the other day on one of my newer projects and +1 to convenience!
-
@chu yeow thanks, coming from you that means a lot :D For those who don't know Chu Yeow is currently the Rails top (non core member) contributor and is from one of my favorite cities: Singapore lah!
-
Hehe I'm only contributing that much because I'm patching Rails instead of working (hope my bosses don't see this). Seriously, most of the time it's something in Rails I wanted to fix for projects at work (and docfixes when I get confused reading the current Rails RDocs).
Anyway, LOL @ "Singapore lah!"


