Search code examples
ruby-on-railsuser-interfacetimezonetime-select

time_select with 12 hour time and Time Zone in Ruby on Rails


I have the need to capture a time and time zone from users of a rails 2.3.8 app, but have been unable to think of a clean solution to create and parse the selections.

Ideally I would have a drop-down menus for the following:

  • hour (1-12)
  • minute (0-59)
  • AM/PM
  • Time Zone

Is there a gem/plugin that accomplishes what I am looking for? Will I need to store both the time and time zone in the database? What is the best strategy for storage?

I'll eventually need to spit these values out in UTC, but a user should be able to go back and review the time in the correct time zone.


Solution

  • You can get time zone selects with the appropriate methods:

    Similarly, there's date_select for dates.

    Storage:

    If the timezone is specific to the user and doesn't change, then store their time zone in their user record and set it when you load the current_user. Rails will convert times to/from UTC and always store UTC in the database and do the automatic convert to that default timezone for you (including daylight savings!). Easiest way to do it.

    use_zone(zone) lets you override the default zone for a block, so you can accept a form value and set it with that function and set your value in that block.

    UPDATE: I wrote up some Rails timezone examples as a blog entry.