12

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?

2 Answers 2

34

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 %>
2
  • 1
    Yes, I saw that link before! Thanks for your help.
    – Rimian
    Aug 21, 2010 at 9:06
  • 4
    The link seems to be outdated and is directing traffic to greek movie reviews?
    – Jay
    Jan 27, 2014 at 22:53
1
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.