6

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.

jessecurry
  • 22,068
  • 8
  • 52
  • 44

2 Answers2

11

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.

wesgarrison
  • 6,975
  • 5
  • 30
  • 39
  • I saw the methods to create a timezone selector, but that selector is not bound to a Time object. Is this binding something that I'll have to do myself? – jessecurry Oct 22 '10 at 13:33
  • A timezone won't be bound to a Time object. Presumably, you're using `form_for @thing` on the thing that you're trying to capture the date/time/zone for. – wesgarrison Oct 22 '10 at 21:58
1

I personally used jQuery to change the display only:

 ampm = ["12 AM","01 AM","02 AM","03 AM","04 AM","05 AM","06 AM","07 AM","08 AM","09 AM","10 AM","11 AM","12 PM","01 PM","12 PM","01 PM","02 PM","01 PM","02 PM","03 PM","04 PM","05 PM","06 PM","07 PM","08 PM","09 PM","10 PM","11 PM"]
    j("#game_start_time_4i option").each(function(index,value){
        j(value).html(ampm[index]);
    });

Rails:

<%= datetime_select('game', 'start_time') %>
Alextoul
  • 839
  • 3
  • 9
  • 19