Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeZone Select field in Ruby on Rails

I want to output one of those select fields for the user to select their timezone. My User model saves the timezone as an integer in seconds. But I can change that if it's not practical.

Something like this:

<select>
  ...
  <option value="x">+9:00 (Darwin, Australia)</option>
  <option value="x">+10:00 (Sydney, Australia)</option>
  ...
</select>

I see that there is a Time Class in Ruby on Rails... Can anyone point me in the right direction?

like image 307
Rimian Avatar asked Aug 21 '10 06:08

Rimian


2 Answers

You can store timezone as a string.

  def self.up
    add_column :users, :time_zone, :string, :limit => 255, :default => "UTC"
  end

Use this to show the select box

<%= f.time_zone_select :time_zone %>
like image 81
Ashwin Phatak Avatar answered Oct 23 '22 08:10

Ashwin Phatak


timezones_diff_and_name = []
  TZInfo::Timezone.all_linked_zones.each do |tz|
    timezones_diff_and_name << {tz.name => tz.current_period.utc_total_offset / (60 * 60)}
  end

  sorted_timezones = timezones_diff_and_name.sort_by { |timezone| timezone.values[0] }

  @timezones = {}
  sorted_timezones.each do |tz|
    diff = tz.values[0]
    name = tz.keys[0]
    @timezones["(GMT#{diff > 0 ? '+':''}#{diff.to_s}h) #{name}"] =  name
  end

Anyone with a better/cleaner solution? I am off to bed :)

like image 1
tiagomatos Avatar answered Oct 23 '22 10:10

tiagomatos